[英]Get attribute from join model (belongs_to) rails
我有2個相關模型。
class Store < ActiveRecord::Base
attr_accessible :name, :subdomain
belongs_to :theme
end
class Theme < ActiveRecord::Base
attr_accessible :name, :description, :screenshot_attributes
has_many :stores
end
一切正常,問題是當我嘗試通過以下方式訪問主題名稱時。
<% @stores.each do |store| %>
<tr>
<td><%= link_to store.subdomain, store %></td>
<td><%= store.name %></td>
<td><%= store.theme.name %></td>
<td><%= link_to 'Go to Store', root_url(subdomain: store.subdomain) %></td>
<td><%= link_to 'Edit', [:edit, store] %></td>
<td><%= link_to 'Destroy', store, confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
這是發生錯誤的行。
<td><%= store.theme.name %></td>
這是消息:
undefined method `name' for nil:NilClass
訪問主題名稱值的正確方法是什么?
謝謝!
僅因為store.theme為零。 一個有用的功能是檢查。 如果您這樣做:
<%= store.inspect %>
您將看到theme_id為nil。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.