【问题标题】:Trouble with Rails 3 has_many :through association and views/formsRails 3 has_many 的问题:通过关联和视图/表单
【发布时间】:2011-09-14 15:32:30
【问题描述】:

我以前在我的旧 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 的 Rails 3 Way 书的部分。任何建议或指示将不胜感激。谢谢!

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案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
    

    然而,这似乎并不是特别理想。对于那些缺席(t)或免责(f)且不包括在场的人,我会用布尔值:status 形成连接,想象它像 meeting_absentees。似乎落后,但这样你的表将有更少的行。

    【讨论】:

    • 谢谢!我感谢您的回复,现在正在尝试这种方法。我一直认为我在表格中选择了错误的协会(fire_fighters v.出席会议)。
    • 很遗憾,它对我不起作用,但我相信我的模型有问题。
    • 再次感谢马克。我遇到的主要问题是,在 fields_for 迭代中,它会在 = f_a_m.object.fire_fighter.xxx 上出错(找不到 fire_fighter 的方法)。基本上,它没有看到任何物体。如果我尝试输出对象(f_a_m.object.to_s 或在调试时使用断点),则不会显示任何内容。我最终在表单视图和会议控制器中提出了一种解决方法,但仍然觉得我缺少管理 has_many :through 关系的核心内容。没什么大不了的,不过……只是更多的阅读要做:)
    • 抱歉,我的回答中有一个错误; fields_for 应该是很多(复数)出席会议。检查编辑。
    • 现在进展顺利,马克。再次感谢,并为忘记注意您的答案是您的答案而道歉...今天早上修复了该错误:)。
    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    相关资源
    最近更新 更多