我有以下模型,其中UserTreatment本质上是一个查找表,但它有另一个名为instance_cost的字段,它存储一个针对每个关系的整数。
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>£</span> <%= pt.input :instance_cost, :as => :string, wrapper: false, label: false %></td>
</tr>
<% end %>
end
我需要做两件事。
答案 0 :(得分:2)
当您为嵌套关联执行fields_for时,您需要在User模型中添加以下内容:
accepts_nested_attributes_for :user_treatments
否则,它不会保存信息。
要访问治疗的名称,您可以通过表单创建者对象的对象方法,如下所示:
<%= f.fields_for :user_treatments do |pt| %>
<tr>
<td><%= pt.object.treatment.name %></td>
...
</tr>
<% end %>