【问题标题】:putting has_many :through into play and using it in an actual form使用 has_many :through 并以实际形式使用它
【发布时间】:2011-05-17 17:51:40
【问题描述】:
class Allowedevent < ActiveRecord::Base
    :belongs_to :room
    :belongs_to :event
end

class Room < ActiveRecord::Base
    :has_many :allowedevents
    :has_many :events => :through => allowedevents
end

class Event< ActiveRecord::Base
    :has_many :allowedevents
    :has_many :rooms=> :through => allowedevents
end

我很难将上述关系放入表格或在控制台中玩弄它们。

问题:

  • 现在假设我保存了一个房间,我是否必须将 ID 显式添加到 allowedevents 表中? 我必须这样做吗?

    房间 = Room.new; room.title = "测试"; room.allowedevents = ""...?

    从上面可以看出,我不知道如何保存实际记录。

  • 基本上我想问如何使用上述关系将房间保存到具有许多allowedevents 的数据库中。我是否必须遍历用户输入并将每个输入保存到allowedevents?有没有更好的办法?

  • 我从 railscasts 剧集中得到了以上内容,railscasts 上是否有一个剧集真正说明了如何在前端使用它?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord railscasts


    【解决方案1】:

    前端可以是房间的编辑页面,将所有事件列为一组复选框。然后,您可以检查允许为该房间保留的活动。

    在房间模型中处理这个有点棘手。有些人会推荐使用accepts_nested_attributes_for,但是当用户稍后取消选中这些框时,它不会自动删除关系。

    accepts_nested_attributes_for 方法具有删除记录的选项,但强制您为要处理的每条记录传入单独的“_delete”参数。如果您想在有人取消选中该框后使用 javascript 将虚拟“_delete”参数添加到表单中,这一切都很好,但如果您不想依赖 javascript,它会变得很棘手。

    因此,我决定放弃 accept_nested_attributes_for 并推出我自己的解决方案,这可能类似于 Ryan Bates 在 accept_nested_attributes_for 存在之前解决此问题的方式。

    这里没有发布我的解决方案,而是指向旧 RailsCast 剧集的链接,它解释了如何处理复杂表单中的嵌套模型:

    http://railscasts.com/episodes/73-complex-forms-part-1

    如果其他人有一种新颖的方法来在 has_many :through style 关系中使用带有复选框的accepts_nested_attributes_for,我很想听听。

    【讨论】:

      猜你喜欢
      • 2012-03-09
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 2017-01-03
      相关资源
      最近更新 更多