【问题标题】:Ruby on Rails: Polymorphic Association, associating tablesRuby on Rails:多态关联,关联表
【发布时间】:2014-03-24 18:13:16
【问题描述】:

我正在研究多态关联,但如何正确调用数据库中的某些值。

如果我有这些表

书桌

 id | title            
  1 | give me something
  2 | more title names please

作者表

 id | name
  1 | Author Goods

审核表

 id | author_id | reviewable_id | reviewable_type | review
 1  |    1    |       1       |       Book        | Don't read this book
 2  |    2    |       2       |       Book        | This book is awesome
 3  |    2    |       1       |      Author       | Love this author

我的控制器如下所示:

@reviews = Review.where(user_id: current_user)

我的 html 循环如下:

<% @reviews.each do |r| %>
  <%= r.author %> <!-- this will give me author information -->
<% end %>

使用r.author,我可以从作者那里获取信息,但是如果我尝试使用reviewable_type 访问作者和书籍的信息怎么办?我不能做r.reviewable_type,因为没有 id 关联。如果我的 Review 表中没有 book_idauthor_id,如果我通过可审查类型的唯一关联是名称,我如何获取 Book 信息的表不是 id?

我希望我对我的问题的解释是有道理的。

【问题讨论】:

  • 为什么没有id?如果它是关联的,那么我不明白为什么没有 reviewable_id。
  • @sonnyhe2002 我的 reviewable_id 在那里。但它只连接到关联的 reviewable_type 名称,但我不确定用什么 Ruby 语法来获取与 reviewable_typereviewable_id 关联的 id

标签: ruby-on-rails ruby ruby-on-rails-3 associations polymorphic-associations


【解决方案1】:

首先,如果它是多态的,则在 Review 中不需要 author_id。

你的 review.rb 应该是这样的

class Review < ActiveRecord::Base
    belongs_to :reviewable, polymorphic: true
end

还有你的 book.rb

class Book < ActiveRecord::Base
    has_many :reviews, as: :reviewable, dependent: :destroy
end

您的 author.rb 也应该类似

现在你不需要直接查询评论表,如果你想要所有 current_user 评论 简单地做

@reviews = current_user.reviews

它将从 reviews table 获取所有具有 reviewable_id == current_user.id 和 reviewable_type == "User" 的记录

你也可以类似地查询书评。

【讨论】:

  • 我想在每篇评论中引用作者姓名。这样我可以做 1 个循环,然后那个循环,我就可以得到作者的名字、评论以及我能得到的任何其他东西。
  • 你可以像@reviews.each { |r| 一样循环访问“@reviews” r.reviewable.name } 如果 reviewable_type 是“作者”,它会给你作者姓名
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
  • 1970-01-01
相关资源
最近更新 更多