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?(fact开发者_运维技巧or) %>
<%= 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 ^^).
First, correct the association and update your results.
class Factor < ActiveRecord::Base
has_many :risks
has_many :outbreaks, :through => :risks
end
精彩评论