2013-01-19 127 views
1

本質上,我有以下,我試圖在我的報價表格中使用collection_select從company.addresses關係中爲我的報價模型中的has_one:地址字段分配一個地址。在IRB中,我可以簡單地引用quote1.address = company1.addresses.first等,並且quote_id列將填充在地址實例中的appropiated中。如何使用select或collection select?

現在,這個數據庫設置可能看起來很簡單,可能是實現這些關係的一種更好的方式,但由於可尋址類型和字段正在改變爲引用關係,多態地址給我帶來了問題,因此從公司地址關係。無法弄清楚如何克隆它們。但是,無論如何,有沒有人有建議如何使用下面的數據庫設置完成我的報價表格中的第一個問題?

class Address < ActiveRecord::Base 
    belongs_to :company 
    has_many :quotes 
    attr_accessibles ... 
    ..... 
end 

class Company < ActiveRecord::Base 
    has_many :addresses 
    accepts_nested_attributes_for :addresses 
    has_many :quotes 
    attr_accessibles ... 
    .... 
end 

class Quote < ActiveRecord::Base 
    belongs_to :address 
    belongs_to :company 
    accepts_nested_attributes_for :address 
    ... attr_accessibles .... 
    .... 
end 

你們會推薦引號和地址之間的連接表嗎?並保持公司和地址一對多?

回答

1

製作另一張表格,將您的報價加入地址。

創建一個新的腳手架。

$ rails g scaffold NewTable quote_id:integer address_id:integer 

用此代碼替換窗體。我無法測試它,但它應該相當準確。

<%= form_for @new_table do |f| %> 
    <%= f.hidden_field(:quote_id, value: @quote.id) %> 
    <%= f.collection_select(:new_table, :address_id, Address.all, :id, :name, :prompt => true) %> 
<% end %> 

您可以在需要的地方accept_nested_attributes_for此NewTable。

+0

是的,我最終選擇了address_id,一個報價只需要一個地址,所以地址和報價之間的一對一運作良好,我最終做了f.address_id,@ available_address.collect {| a | [a.line1,a.id]}等。另外,一個腳手架將是矯枉過正。感謝您的建議。 – TheIrishGuy