Rails 3 has_many的问题has_many:通过关联和视图/表单

问题描述:

我以前在旧的Rails应用程序中使用过has_and_belongs_to_many关联,但我正在转向使用has_many :: through来创建新的和当前的应用程序。但是,我相信我错过了has_many的核心:通过Rails 3中的关联。Rails 3 has_many的问题has_many:通过关联和视图/表单

目前,我正在为我们城镇的志愿者消防部门构建一个应用程序。当我们开会时,我们要检查一下消防员是否在场,放弃或不在场。

我的模型:

#FireFighter Model 
class FireFighter < ActiveRecord::Base 
has_many :attendance_meetings 
has_many :meetings, :through => :attendance_meetings 
accepts_nested_attributes_for :meeting 

#Meeting Model 
class Meeting < ActiveRecord::Base 
has_many :attendance_meetings 
has_many :fire_fighters, :through => :attendance_meetings 
accepts_nested_attributes_for :fire_fighter 

#AttendanceMeeting Model 
class AttendanceMeeting < ActiveRecord::Base 
attr_accessor :status # this is the added property on the join model that we need populated 
belongs_to :fire_fighter 
belongs_to :meeting 

我遇到的问题是如何在视图中设置此。目前,我有:

= hidden_field_tag "meeting[fire_fighter_ids][]" 
[email protected]_fighters.each do |fire_fighter| 
    = fire_fighter.fire_fighter_name 
    %span.radio_btn= radio_button_tag :fire_figher_ids, fire_fighter.id, "present" 
    present 
    %span.radio_btn= radio_button_tag :fire_figher_ids, fire_fighter.id, "excused" 
    excused 
    %span.radio_btn= radio_button_tag :fire_figher_ids, fire_fighter.id, "absent" 
    absent 
    %br 

这将吐出的每个消防战士和三个单选按钮,每个消防员(与目前的选择,为自己开脱,或不存在)。然而,由此产生的单选按钮的名称都是一样的,所以你只能选择一个消防战士。

正如我上面提到的,我觉得我缺少一些基本的东西,但我很难过。我已经阅读了大量的SO问题以及ActiveRecord上Rails 3 Way书的章节。任何建议或方向将不胜感激。谢谢!

它应该是这样的:

class Meeting < ActiveRecord::Base 
    has_many :attendance_meetings 
    has_many :fire_fighters, :through => :attendance_meetings 
    accepts_nested_attributes_for :attendance_meetings 

# view 
= form_for @meeting do |f| 
    = f.fields_for :attendance_meetings do |f_a_m| 
    = f_a_m.object.fire_fighter.name 
    = f_a_m.check_box :status, 'present' 
    = f_a_m.check_box :status, 'excused' 
    = f_a_m.check_box :status, 'absent' 

对于你正在做你需要建立与本次会议的每个消防员的关联方式。例如:

@meeting.firefighters << Firefighter.all 

但是,这看起来并不是特别理想。对于那些缺席(t)或原谅(f)而现在不包括在内的人,我会用布尔:状态来形成连接,想象它像meeting_absentees。似乎落后,但这样你的表格将会有更少的行。

+0

谢谢!我很欣赏这种回应,现在正在尝试这种方法。我一直认为我在形式上的错误关联(fire_fighters v。attendance_meeting)。 –

+0

不幸的是,它不适合我,但我相信,我的模型中有一些不妥之处。 –

+0

你收到了什么错误? – mark