views:

20

answers:

1

I have the following models

class Outbreak < ActiveRecord::Base
    has_many :risks
    has_many :factors, :through => :risks
end

class Risk < ActiveRecord::Base
    belongs_to :outbreak
    belongs_to :factor
end

class Factor < ActiveRecord::Base
    has_many :risks
    has_many :outbreaks, :through => :risks
end

Risk table
id : integer
outbreak_id : integer
factor_id : integer
details : text

In view/outbreak/edit

   <div id="factor_div">
    <% for factor in Factor.find(:all, :conditions => {:outbreak_type => @outbreak.outbreak_type}) %>
        <div>
        <%= check_box_tag "outbreak[factor_ids][]", factor.id , @outbreak.factors.include?(factor) %>
        <%= factor.name %>
        <%= text_field_tag "risk[details][]", @outbreak.risks.each{ |risk| if risk.factor_id == factor.id; risk} %>
        </div>

    <% end %>
   </div>

I'm trying to edit the Risk model details attribute (and populate the correct text_field from the @outbreak.risks array). Is it possible to do that using the approach of iterating through the Factors (which a table of mainly static variables - which have to occassionally altered by the end-users) and then checking whether or not each outbreak.risk has that factor_id or am i just going about this the wrong way?

(can't think - its friday afternoon and sunny out.... and theres a beer garden down the road ^^).

A: 

First, correct the association and update your results.

class Factor < ActiveRecord::Base
  has_many :risks
  has_many :outbreaks, :through => :risks
end
Shreyas Satish
Cheers Shreyas - completely missed that association :D, I've edited the code in the question to include it
Pasted
Try using formtastic. All the associations , while creating forms such as these are managed automatically, with minimum fuss.
Shreyas Satish
Thanks for the input Shreyas - I did go through Formtastic (railscasts ofc!) and it seems fine for a HABTM association with checkboxes - the railscasts tutorial goes over this really well (although populating the link table directly isn't that obivous and will probably need some kind of additional function in the model to get and set the attribute). But... as always is the case client has changed their mind and wanted something different!
Pasted