在Rails中通过嵌套表单构建多态has_many

时间:2014-02-06 23:46:59

标签: ruby-on-rails polymorphism nested-forms has-many-through

好的,所以我不想问,但我太依旧了。

Users 拥有许多Stands(如展位)Permissions

所以我的注册控制器看起来像这样:

def new
  @registree = User.new
  @registree.build_company
  @registree.permissions.build.build_stand
end

我的表格看起来像这样:

<%= simple_form_for @registree, url: register_path do |f| %>
  ... stuff ...
  <%= f.simple_fields_for(:permissions) do |perms| %>
    <%= perms.simple_fields_for(:stands) do |stand| %>
      ... stuff ...
    <% end %>
  <% end %
<% end %>

它有效!

然后客户希望Users也有许多Pavilions(展览期限)。

所以我决定让我的has_many通过关系多态。

所以现在我的Permission模型如下所示:

class Permission < ActiveRecord::Base
  attr_accessible :level, :user_id, :ownable_id, :ownable_type, :ownable_attributes

  belongs_to :ownable, polymorphic: true
  belongs_to :user

  accepts_nested_attributes_for :ownable
end

现在,ownable_type可以是StandPavilion

这适用于一些简单的测试。

魔术。

但我无法理解如何为此构建嵌套表单。

因此,我的新发现的多态性注册控制器中的这一行会引发错误

@registree.permissions.build.build_stand

哪种方式有道理,因为与Permission模型中的展位没有直接关系,而是ownable的东西,可以是展台或展馆。

所以我尝试了build_ownable这也不起作用。

然后我尝试简单地绕过表单中的Permission嵌套。

在控制器中使用

@registree.stands.build

这在我的User模型中。

accepts_nested_attributes_for :stands

这让我显示和提交表单,但它从未创建过立场。很明显,这种关系并没有在那里正确建立。

请问有人伸出援助之手吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

polymorphic association中,你必须像这样定义:

class Permission < ActiveRecord::Base
  belongs_to :permissable, polymorphic: true
  belongs_to :user
end

class Stand < ActiveRecord::Base
   has_many :permissions, as: :permissable
end

class User < ActiveRecord::Base
  has_many :permissions
end

class Pavilion < ActiveRecord::Base
  has_many :permissions, as: :permissable
end