Rails 3的麻烦has_many:通过关联和视图/表单

时间:2011-09-14 15:32:30

标签: ruby-on-rails activerecord associations

我以前在旧的Rails应用程序中使用了has_and_belongs_to_many关联,但我正在转向使用has_many,:through用于新的和当前的应用程序。但是,我相信我错过了has_many的核心内容:通过Rails 3中的关联。

目前,我正在为我们镇的志愿者消防部门建立一个应用程序。当我们开会时,我们想要检查消防员是否存在,原谅或缺席。

我的模特:

#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][]"
-@meeting.fire_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的The Rails 3 Way书的部分。任何建议或方向将是最受欢迎的。谢谢!

1 个答案:

答案 0 :(得分:1)

应该是这样的:

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

然而,这似乎并不特别优化。我会用一个boolean:s​​tatus来表示那些缺席(t)或原谅(f)但不包含礼物的人,想象它就像meeting_absentees。看似向后,但这样你的表将有更少的行。