accepts_nested_attributes_for 与belongs_to 多态 [英] accepts_nested_attributes_for with belongs_to polymorphic

查看:26
本文介绍了accepts_nested_attributes_for 与belongs_to 多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想与 accepts_nested_attributes_for 建立多态关系.代码如下:

I would like set up a polymorphic relation with accepts_nested_attributes_for. Here is the code:

class Contact <ActiveRecord::Base
  has_many :jobs, :as=>:client
end

class Job <ActiveRecord::Base
  belongs_to :client, :polymorphic=>:true
  accepts_nested_attributes_for :client
end

当我尝试访问 Job.create(..., :client_attributes=>{...} 给我 NameError: uninitialized constant Job::Client

When I try to access Job.create(..., :client_attributes=>{...} gives me NameError: uninitialized constant Job::Client

推荐答案

刚刚发现 rails 不支持这种行为,所以我想出了以下解决方法:

Just figured out that rails does not supports this kind of behavior so I came up with the following workaround:

class Job <ActiveRecord::Base
  belongs_to :client, :polymorphic=>:true, :autosave=>true
  accepts_nested_attributes_for :client

  def attributes=(attributes = {})
    self.client_type = attributes[:client_type]
    super
  end

  def client_attributes=(attributes)
    self.client = type.constantize.find_or_initialize_by_id(attributes.delete(:client_id)) if client_type.valid?
  end
end

这让我可以像这样设置表单:

This gives me to set up my form like this:

<%= f.select :client_type %>
<%= f.fields_for :client do |client|%>
  <%= client.text_field :name %>
<% end %>

不是确切的解决方案,但想法很重要.

Not the exact solution but the idea is important.

这篇关于accepts_nested_attributes_for 与belongs_to 多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆