4

ホームページにレビューのリストを表示し、同時に各レビューの評価を表示しようとしています。

(関連付けられた review_id に基づいて) 各レビューに添付されたさまざまな評価のコンマ区切りのリストが必要です。評価は -5 から 5 の整数です。ページを読み込んだときに得られるのは次のとおりです。

Review 1. #<ActiveRecord::Relation:0x007f9879749a50>
Review 2. #<ActiveRecord::Relation:0x007f9879749a50>
Review 3. #<ActiveRecord::Relation:0x007f9879749a50>
Review 4. #<ActiveRecord::Relation:0x007f9879749a50>
Review 5. #<ActiveRecord::Relation:0x007f9879749a50>

これを見たいとき:

Review 1. 1, 5, 2, -3
Review 2. 2, -1
Review 3. 1, 1, 4, 5
Review 4. -5, -2, -3
Review 5. 1, 1, 3, 2, 1, 5, 3, 2

ユーザーモデル:

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :ratings_attributes, :reviews_attributes

  has_many :reviews, dependent: :destroy
  has_many :ratings, :through => :reviews, dependent: :destroy
  accepts_nested_attributes_for :ratings, allow_destroy: true
  accepts_nested_attributes_for :reviews, allow_destroy: true
end

モデルのレビュー:

class Review < ActiveRecord::Base
  attr_accessible :content, :priority, :ratings_attributes
  belongs_to :user
  has_many :ratings
end

評価モデル:

class Rating < ActiveRecord::Base
  attr_accessible :rating_count, :review_id, :timestamp, :user_id

  belongs_to :user
  belongs_to :review
end

ホームコントローラー:

class HomeController < ApplicationController

  def index
    @reviews = current_user.reviews.order("position")
    @ratings = Rating.where(params[:review_id])
    @ratings_list = Rating.find(:all)
  end

index.html.erb

<h1>Listing reviews</h1>
<p id="notice"><%= notice %></p>
<br />
  <div class="span12">

<ul id="reviews" data-update-url="<%= sort_reviews_url %>">
    <% @reviews.each do |review| %>
        <%= content_tag_for :li, review do %>
            <span class="handle">[drag]</span>
            <%= link_to h(review.content), review %>

            <!-- this is where i want a comma separated list of the different ratings attached to each review; ratings are integers of -5 to 5. -->
            <%= @ratings %>

        <% end %>
    <% end %>
</ul>

<br />
  </div>
<!-- for debugging that i'm actually getting through to the ratings data -->
<%= @ratings_list %>
<br />

<%= link_to 'New Review', new_review_path %>

私の人生では、コントローラーで何か間違ったことをしているのか、html で何か間違っているのかわかりません。

各レビューの横に表示されるのは、次のようなものです。

#<ActiveRecord::Relation:0x007f987a9d7618>

前もって感謝します...そしてもし気にかけているなら、私は外で働いていて、虫が私の鼻に飛んできました.

4

2 に答える 2

6

おそらく、それらの文字列表現ではなく、実際のレビュー オブジェクトをレンダリングしています。このようなものがビューで機能するはずです:

<%= @ratings.map { |rating| rating.rating_count }.join(", ") %>

これにより、評価のコレクションが rating_counts のコレクションになり、コンマで結合されます。

私は鼻の上のバグを助けることはできません:)

于 2013-03-31T21:46:07.983 に答える
1

クエリはレールで遅延実行されます。したがって、次のようなObject.where(...)ことを行うと、リレーション オブジェクトが返されます (ご覧のとおり)。実際に使用した場合にのみ実行されます(つまり、ループまたは呼び出し.all(ただし.all、Rails 4でわずかに変更されていると思います))。コンマ区切りのリストを取得するには、<%= @ratings.map(&:rating_count).join(', ') %>.

于 2013-04-01T01:38:40.393 に答える