2014-03-27 54 views
1

我正在使用collection_check_boxes通过关系在has_many中创建对象; 这里有些型号:select_check_boxes与一个有很多直通关系和:checked选项

#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 

当我创建一个报告我也有collection_check_box选择情绪我要绑定到该报告(通过模型EmotionalState)的列表正如你可以理解;一切工作在创建(我检索散列值,如果@ report.save我也创建EmotionalStates与@ report.id和@ emotion.id。)

但是,当它来编辑报告我想编辑还有相关的EmotionalStates(这意味着创建新的EmotionalStates或删除旧的EmotionalStates)。

如何使用所有可用的情绪填充select_check_boxes,检查是否通过EmotionalStates项目关联了情感?

如果我写的是这样的:

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

我会为每alredy相关情绪的未选中的复选框。

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

虽然这个代码将正确返回Emotion.all,但不会检查alredy有关通过@ report.emotional_states到@report情绪。

我找遍了所有周围的wheb上的的用法示例:检查collection_select_boxes选项没有任何结果... 任何暗示?

回答

0

回来这个错误之后,我发现这个问题是一个不正确的使用.MAP的方法,映射整个对象(e.emotion)而不是它的id(e.emotion.id)。

这很容易固定我的问题:

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

谢谢您的帮助!

0

我在这个way.you做了同样的一次也可以尝试:

Emotions: 
     <% Emotion.all.each do |emotion| %> 

     <%= check_box_tag 'report[emotion_ids][]' , emotion.id, @report.emotion.include?(emotion) %><%= emotion.name %><br/> 
     <% end %> 

在控制器添加到:emotion_ids=>[]强参数。

一线到控制器更新方法: PARAMS [:报告] [:emotion_ids] || = []