2013-06-02 22 views
1

我有以下模型,其中UserTreatment基本上是查找表,但它具有另一個稱爲instance_cost的字段,它存儲每個關係的整數。用simple_form_for代表關聯模型

class User < ActiveRecord::Base 
    has_many :user_treatments 
    has_many :users, :through => :user_treatments 
end 

class UserTreatment < ActiveRecord::Base 
    attr_accessible :instance_cost 

    belongs_to :user 
    belongs_to :treatment 
end 

class Treatment < ActiveRecord::Base 
    attr_accessible :name 

    has_many :user_treatments 
    has_many :users, :through => :user_treatments 
end 

所以我可以做這樣的事情來獲得用戶ID 14

1.9.3p429 :181 > User.find(14).user_treatments.first.instance_cost 
=> 100 

一審成本,這得到治療的名字

1.9.3p429 :181 > User.find(14).user_treatments.first.treatment.name 
=> "Sports Massage" 

但是我有一個問題代表他們在一個形式使用simple_form_for

<% simple_form_for @user do |f| %> 

    # This sucessfully gives us the checkboxes of all treatments and stores them in the UserTreatments table 
<%= f.collection_check_boxes(:treatment_ids, Treatment.all, :id, :name) %> 

<%= f.fields_for :user_treatments do |pt| %> 
     <tr> 
      <td> 
       <!-- I WANT THE NAME OF THE TREATMENT HERE --> 
      </td> 
      <td><span>&pound;</span> <%= pt.input :instance_cost, :as => :string, wrapper: false, label: false %></td> 
     </tr> 
    <% end %> 
end 

我需要做兩件事。

  1. 顯示處理的名稱(我怎麼也表達User.user_treatments.treatment.name與simple_form?)
  2. 正確設置instance_cost。它目前沒有設置。

回答

2

當你fields_for嵌套的關聯,那麼你需要添加以下您的用戶模式:

accepts_nested_attributes_for :user_treatments 

否則,將不保存信息。

以及訪問處理的名稱,你可以去通過表單創建者對象的對象方法,就像這樣:

<%= f.fields_for :user_treatments do |pt| %> 
    <tr> 
    <td><%= pt.object.treatment.name %></td> 
    ... 
    </tr> 
<% end %>