[英]How to span belongs_to and has_many relationship in rails?
I have the models below: 我有以下型号:
class Origtext < ActiveRecord::Base
attr_accessible :book, :chapter, :textual, :verse
has_many :reviews
end
class Review < ActiveRecord::Base
belongs_to :origtext
attr_accessible :description
end
The below collects all origtexts where the book is 'Bible' 以下收集书籍为“圣经”的所有原文
@origtexts = Origtext.where(:book => 'Bible')
What is the ruby code for how to collect all reviews associated with a certain book? 如何收集与某本书相关的所有评论的红宝石代码是什么?
Posting code to iterate through reviews: 发布代码以迭代评论:
# @reviews.each do |review|
# puts review
# end
Try this in your console: 在你的控制台中尝试这个:
@origtexts = Origtext.where(:book => 'Bible')
@origtexts.each do |orig_text|
puts orig_text.name
puts orig_text.reviews # puts the reviews associated with the orig_text
end
Or with an id: 或者带有id:
@origtext = Origtext.where(id: params[:id]).first
@origtext.reviews # returns the reviews associated with the origtext
Or directly from the Review model: 或直接来自Review模型:
the_holy_bible = Origtext.where(:book => 'Bible').first
@reviews = Review.where(origtext_id: the_holy_bible.id)
它应该像以下一样简单:
@reviews = @origtexts.each(&:reviews)
@reviews = Review.where(:origtext => { :book => 'Bible' })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.