0

parent屬性我有五款車型:軌道4一個一對多的關係:找到孩子PARENT_ID屬性

class User < ActiveRecord::Base 
    has_many :administrations 
    has_many :calendars, through: :administrations 
    has_many :comments 
end 

class Calendar < ActiveRecord::Base 
    has_many :administrations 
    has_many :users, through: :administrations 
    has_many :posts 
end 

class Administration < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :calendar 
end 

class Post < ActiveRecord::Base 
    belongs_to :calendar 
end 

class Comment < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :user 
end 

comment表有以下欄目:idpost_iduser_idbody

在不同的視圖中,例如在show.html.erb張貼視圖中,我需要顯示相關注釋,其中user的名字發佈了comment

換句話說,我試圖從comment.user_id檢索user.first_name

要做到這一點,我在comment.rb文件中定義了以下方法:

def self.user_first_name 
    User.find(id: '#{comment.user_id}').first_name 
end 

,然後我更新了show.html.erb後視圖如下:

<h3>Comments</h3> 
<% @post.comments.each do |comment| %> 
    <p> 
    <strong><%= comment.user_first_name %></strong> 
    <%= comment.body %> 
    </p> 
<% end %> 

當我這樣做,我得到出現以下錯誤:

NoMethodError in Posts#show 
undefined method `user_first_name' for #<Comment:0x007fc510b67380> 
<% @post.comments.each do |comment| %> 
    <p> 
    <strong><%= comment.user_first_name %></strong> 
    <%= comment.body %> 
    </p> 
<% end %> 

我真的沒有erstand爲什麼我會收到與Posts#show有關的錯誤。

任何想法如何解決這個問題?

+0

你保存視圖? :D在錯誤中看到這個「<%= comment.user_name%>」。並看看你發佈的代碼..:p –

+0

是的,我做到了。抱歉讓我感到困惑:在我開始寫這個問題的那一刻和我發表它的那一刻之間,我嘗試了一些不同的東西。我相應地更新了問題,並確認我仍然得到相同的錯誤。 –

+1

那麼'def self.user_first_name'必須是'def user_first_name' –

回答

2

替換:

comment.rb

def self.user_first_name 
    User.find(id: '#{comment.user_id}').first_name 
end 

有:

comment.rb

delegate :first_name, to: :user, prefix: true 

如果你這樣做,你可以做同一通話comment.user_first_name,它會給你用戶的名字。如果用戶沒有first_name,您不希望它中斷,請添加, allow_nil: true

您可能還需要添加:

has_many :comments

user.rb

class User < ActiveRecord::Base 
    has_many :administrations 
    has_many :calendars, through: :administrations 
    has_many :comments 
end 
+1

非常感謝。'委託:名字,到::用戶,前綴:真正'工作。我覺得應該有一種更好的方式來實現我想要的,而不是我想要對待幫手的方式,而這正是您的建議。它完美的作品。還要感謝你在'user'模型中對'has_many:comments'的更新:它已經被這樣定義了,我剛剛發佈了我的問題。無論如何,再次感謝。 –

+1

任何時候,如果您有任何其他問題,請隨時聯繫我們! – DerProgrammer

+0

非常感謝,非常感謝。 –