ActiveRecord ::显示而不是预期数据的关系代码

时间:2013-03-31 21:41:43

标签: ruby-on-rails activerecord controller associations nested-attributes

我正在尝试在我的主页上显示评论列表,同时显示每个评论的评分。

我想要一个逗号分隔的每个评论附带的不同评级列表(基于相关的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>

提前感谢...如果你在意的话,我在外面工作,一只虫子飞了起来。

2 个答案:

答案 0 :(得分:6)

您可能正在渲染实际的审阅对象,而不是它们的字符串表示形式。这样的东西应该在视图中起作用:

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

将您的评分集合转换为rating_counts的集合,然后用逗号连接它们。

我无法帮助缓解鼻子的问题:)

答案 1 :(得分:0)

查询在rails中延迟执行。因此,当您执行Object.where(...)之类的操作时,它会返回关系对象(就像您所看到的那样)。它只会在您实际使用它时执行(即循环或调用.all(尽管我相信.all在rails 4中略有变化))。要获得以逗号分隔的列表,您只需执行<%= @ratings.map(&:rating_count).join(', ') %>