简体   繁体   English

Ruby on Rails:多态关联,关联表

[英]Ruby on Rails: Polymorphic Association, associating tables

I'm working on polymorphic association, but how do I correctly call certain values in my database. 我正在研究多态关联,但是如何正确调用数据库中的某些值。

If I have these tables 如果我有这些桌子

Book table 书桌

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

Author table 作者表

 id | name
  1 | Author Goods

Review table 审查表

 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

My controller looks like this: 我的控制器如下所示:

@reviews = Review.where(user_id: current_user)

My html loops like this: 我的html循环是这样的:

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

With r.author , I can get information from author, but what if I'm trying to access information of author and book with reviewable_type? 使用r.author ,我可以从author那里获取信息,但是如果我尝试使用r.author访问author和book的信息怎么办? I can't do r.reviewable_type because, theres no id association. 我无法执行r.reviewable_type因为没有id关联。 If I don't have the column book_id like author_id in my Review table, how do I get Book information if my only association through reviewable type is the name of the tables not the id? 如果我的Review表中没有author_id book_id列,那么如果我通过可审核类型唯一的关联是表名而不是ID,我如何获得Book信息?

I hope my explanation of my issue makes sense. 我希望我对我的问题的解释是有意义的。

firstly u dont need author_id in Review if it is polymorphic. 首先,如果它是多态的,则不需要在Review中的author_id。

your review.rb should look like 您的review.rb应该看起来像

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

and your book.rb 和你的book.rb

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

similar should be for your author.rb also 类似的也应该适合您的author.rb

now u dont need to query Review table directly , if u want all current_user reviews simply do 现在,您不需要直接查询Review表,如果您只想全部current_user评论

@reviews = current_user.reviews

it will fetch all records from reviews table which have reviewable_id == current_user.id and reviewable_type == "User" 它将从reviews table中获取具有reviewable_id == current_user.id和reviewable_type ==“ User”的所有记录

u can similarly query for Books reviews also. 您也可以类似地查询书评。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM