2013-05-03 97 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

相關問題