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
表有以下欄目:id
,post_id
,user_id
和body
。
在不同的視圖中,例如在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
有關的錯誤。
任何想法如何解決這個問題?
你保存視圖? :D在錯誤中看到這個「<%= comment.user_name%>」。並看看你發佈的代碼..:p –
是的,我做到了。抱歉讓我感到困惑:在我開始寫這個問題的那一刻和我發表它的那一刻之間,我嘗試了一些不同的東西。我相應地更新了問題,並確認我仍然得到相同的錯誤。 –
那麼'def self.user_first_name'必須是'def user_first_name' –