Search code examples
ruby-on-railsrubycheckedform-helpers

select_check_boxes with an has many through relation and :checked option


I am using collection_check_boxes to create object in a has_many through relation; here some models:

#emotion.rb
class Emotion < ActiveRecord::Base
    has_many :emotional_states
    has_many :reports, :through => :emotional_states
end

#report.rb
class Report < ActiveRecord::Base
    has_many :emotional_states
    has_many :emotions, :through => :emotional_states
    [... other "irrelevant" stuff here ...]
end

#emotional_states.rb
class EmotionalState < ActiveRecord::Base
    belongs_to :report
    belongs_to :emotion
end

As you may understand when I create a Report I also select with a collection_check_box a list of Emotions I want to bind to that report (through the model EmotionalState); Everything works on create (I retrieve the hash values and if @report.save I also create EmotionalStates with the @report.id and @emotion.id.)

But when it cames to edit the Report I would like to edit also the associated EmotionalStates (this means creating new EmotionalStates or deleting old one).

How can I populate the select_check_boxes with ALL the available Emotions having checked that emotions that are alredy associated through the EmotionalStates bojects?

If I write something like:

<%= collection_check_boxes(:report, :emotion_id, @report.emotional_states.map{|e| e.emotion}, :id, :name) %>

I'll get a unchecked checkbox for every alredy associated Emotion.

    <%= collection_check_boxes(:report, :emotion_id, Emotion.all, :id, :name, :checked => @report.emotional_states.map{|e| e.emotion}) %>

While this code will correctly returns Emotion.all, but will not check the emotions alredy associated to @report through @report.emotional_states.

I've searched all around the wheb for examples on the usage of :checked options for collection_select_boxes without any results... any hint?


Solution

  • After coming back to this bug I discovered that the problem was an incorrect use of the .map method, mapping a whole object (e.emotion) instead its id (e.emotion.id).

    This easily fixed my problem:

    <%= collection_check_boxes(:report, :emotion_id, Emotion.all, :id, :name, :checked => @report.emotional_states.map{|e| e.emotion.id}) %>
    

    Thank you for your help!