2015-04-27 27 views
0
class PriceList < ActiveRecord::Base 
    has_many :prices, :dependent => :destroy 
end 

和價格:紅寶石 - 訪問parent屬性從子 - 一對多關係

class Price < ActiveRecord::Base 
    belongs_to :price_list 
    belongs_to :material 
    belongs_to :unit 
end 

現在PRICE_LIST指數我想說明價格列表名稱,而不是ID:

<tbody> 
    <% @prices.each do |price| %> 
     <tr> 
     <td><%= price.price_list.price_list_short_name %></td> 
     <td><%= price.materials_id %></td> 
     <td><%= price.units_id %></td> 
     <td><%= link_to 'Show', price %></td> 
     <td><%= link_to 'Edit', edit_price_path(price) %></td> 
     <td><%= link_to 'Destroy', price, method: :delete, data: { confirm: 'Are you sure?' } %></td> 
     </tr> 
    <% end %> 
    </tbody> 

我在做什麼錯,price.price_list.price_list_short_name不起作用?

+0

你會得到什麼錯誤?你可以添加'price_list_short_name'方法嗎? –

+0

'PriceList'中有'price_list_short_name'嗎?你能向我們展示異常嗎? –

+0

您在哪個列中存儲price_list的名稱? –

回答

1

至少有一個Price記錄沒有關聯price_list。解決方案取決於你的意圖。如果要強制所有pricesprice_list,你可以添加驗證:

class Price < ActiveRecord::Base 
    validates :price_list, presence: true 
    # ... 
end 

如果你想允許PRICE_LIST少prices,你可以利用try的方法,來解決這些錯誤的觀點:

price.price_list.try(:price_list_short_name) 

順便說一句,命名您的列price_list_short_nameprice_lists表中有點多餘。

+0

'price.materials_id'表明每個記錄都有關聯的price_list。在數據庫中也檢查了這個。 'price.price_list.try(:price_list_short_name)'什麼都不顯示。試圖將列名從price_list_short_name更改爲short_name。也許這是造成問題? – Robert

0

我錯過了適當的參考。 添加到遷移文件:

class AddReferencesToPrices < ActiveRecord::Migration 
    def change 
    remove_column :prices, :price_list_id 
    remove_column :prices, :materials_id 
    remove_column :prices, :units_id 
    add_reference :prices, :price_list, :index => true 
    add_reference :prices, :material, :index => true 
    add_reference :prices, :unit, :index => true 
    end 
end 

解決了問題。