32423hjh32423
32423hjh32423

Reputation: 3088

Represent associated model with simple_form_for

I have the following models where UserTreatment is essentially a lookup table but it has another field called instance_cost which stores an integer against each relationship.

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

So I can do things like this to get the first instance cost for user id 14

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

and this to get the name of the treatment

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

However I have a problem representing them in a form using 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

There are two things I need to do.

  1. Show the name of the treatment (how do I do express User.user_treatments.treatment.name with simple_form ?)
  2. Set the instance_cost correctly. Its currently not getting set at all.

Upvotes: 1

Views: 87

Answers (1)

DanneManne
DanneManne

Reputation: 21180

When you do fields_for for a nested association then you need to add the following in your User model:

accepts_nested_attributes_for :user_treatments

Otherwise, it will not save the information.

And to access the name of the treatment, you could go through the object method of the form creator object, like this:

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

Upvotes: 2

Related Questions