2012-01-04 100 views
0

與範圍有點掙扎。我有有電話號碼輪廓模型:嵌套屬性的導軌形式

has_many :phone_contact_infos, :dependent => :destroy 
accepts_nested_attributes_for :phone_contact_infos, :reject_if => :all_blank 

..then在我PhoneContactInfo模式,我有..

belongs_to :profile 
scope :business, where('level LIKE ?', 'business') 
scope :mobile, where('level = ?', 'mobile') 

所以基本上一個配置文件可以擁有移動和一個商務號碼。我一直在嘗試的做法是爲每種類型的電話號碼(業務和移動電話)編輯一個編輯表單。這是我這做了錯誤的事情..

<%= form_for @profile do |f| %> 
    <%= f.fields_for :phone_contact_infos do |contact_info| %> 
    <%= contact_info.text_field :country, :size => 2 %> 
    <%= contact_info.text_field :city, :size => 5 %> 
    <%= contact_info.text_field :number, :size => 8 %> 
    <% end %> 
<% end %> 

..since我有兩個數據庫條目(一個用於手機和其它業務)上面的代碼中插入一個表格爲每種類型的,所以我結束了用於商業和手機號碼的文本字段。我只想編輯一個號碼,比如手機。我想我需要在上面的代碼中進行更改,以便在上面的PhoneContactInfo模型中定義範圍。

謝謝!

回答

0

以下是一種方法。

你可以改變has_many關係在您的個人資料模型,包括條件:

has_many :mobile_phone_contact_infos, :class_name => "PhoneContactInfo", :conditions => {:level => "mobile"}, :dependent => :destroy 
has_many :business_phone_contact_infos, :class_name => "PhoneContactInfo", :conditions => {:level => "business"}, :dependent => :destroy 

在你看來那麼你可以使用:

<%= f.fields_for :mobile_phone_contact_infos do |contact_info| %> 

...它只會拔出手機聯繫,而不是商業號碼。

有兩點需要注意:

  1. 雖然你可以使用:conditions => {}條款(如where('level LIKE ?', 'business'))原始SQL條件下,你失去了一些功能。在我上面的代碼中,如果你的profile.mobile_phone_contact_infos.build Rails會智能地爲你填充'level'字段 - 但是如果你使用原始的SQL代碼則不會。
  2. 我還沒有測試過這個,過去我只在關聯是多態時使用:conditions。我無法確認是否有必要使您的功能正常工作。

祝你好運!

+0

感謝搶劫,會試試這個。 – absolutskyy 2012-01-05 22:49:19