【发布时间】: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_id 列 author_id,如果我通过可审查类型的唯一关联是名称,我如何获取 Book 信息的表不是 id?
我希望我对我的问题的解释是有道理的。
【问题讨论】:
-
为什么没有id?如果它是关联的,那么我不明白为什么没有 reviewable_id。
-
@sonnyhe2002 我的 reviewable_id 在那里。但它只连接到关联的
reviewable_type名称,但我不确定用什么 Ruby 语法来获取与reviewable_type和reviewable_id关联的 id
标签: ruby-on-rails ruby ruby-on-rails-3 associations polymorphic-associations