2013-05-03 118 views
0

我有以下型号:如何在rails中跨越belongs_to和has_many关系?

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 

下面收集所有origtexts这里的书是“圣经”

@origtexts = Origtext.where(:book => 'Bible') 

什么是如何收集与某本书相关的所有评论Ruby代码?

发布代码通过审查迭代:

# @reviews.each do |review| 
    # puts review 
    # end 
+0

你要为这个特定本书所有的评论? – Mindbreaker 2013-05-03 18:16:05

回答

2

试试这个在您的控制台:

@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 

或与编号:

@origtext = Origtext.where(id: params[:id]).first 
@origtext.reviews # returns the reviews associated with the origtext 
从审查模式

或者直接:

the_holy_bible = Origtext.where(:book => 'Bible').first 
@reviews = Review.where(origtext_id: the_holy_bible.id) 
+0

我在Origtext下有多个条目,具有书籍的“圣经”属性。我发现最后2种方法每次只返回1次评论,即使我有多个评论,每篇评论都有Origtext中的'Bible'属性。 – sharataka 2013-05-03 18:33:35

0

应该为下面的也很简单:

@reviews = @origtexts.each(&:reviews) 
+0

当我尝试遍历@reviews时,出现错误,提示未定义的方法'description' – sharataka 2013-05-03 18:35:55

+0

您的评论表是否有“说明”列? – 2013-05-03 18:44:37

+0

是的,我确认了。它在review.rb文件中。我也在SQL Lite查看器中看到数据,并看到名为description的列。 – sharataka 2013-05-03 18:46:02

0
@reviews = Review.where(:origtext => { :book => 'Bible' }) 
+0

我试图通过这个迭代...... @ reviews.each do | review | \t puts review.description end ...我得到一个错误,说没有这样的列。 – sharataka 2013-05-03 18:38:15

+0

SQLite3 :: SQLException:no such column:origtext.book:SELECT“reviews”。* FROM“reviews”WHERE“origtext”。“book”='Bible' – sharataka 2013-05-03 18:45:01

相关问题