创建具有多态属性的新实体

时间:2012-01-02 06:33:41

标签: ruby-on-rails activerecord

我正在创建跨三种不同实体类型的标记系统。我在实现它作为一个相关的多态属性时遇到了麻烦。编辑现有联系人似乎有效(它创建了相关记录),但在创建新联系人时,它根本不会创建其他记录。只有一个关联记录,因为每个标记作为单个字符串记录在一个长文本字段中。

contact.rb:

class Contact < ActiveRecord::Base
   has_one :tag, :as => taggable
   accepts_nested_attributes_for :tag, :allow_destroy => true, 
     :reject_if => :all_blank

tag.rb:

class Tag < ActiveRecord::Base
  belongs_to :taggable, :polymorphic => true

contacts_controller.rb:

def new
   @contact = Contact.new
   @contact.tag = Tag.new
end

def edit
  @contact = Contact.find(params[:id])
  if @contact.tag.nil?
    @contact.tag = Tag.new
  end
end

new.html.erb:

<%= fields_for :tag do |tag| %>
<div class="clearfix">
  <%= tag.label :tags, 'Tags' %>
  <div class="input">
    <%= tag.text_field :tags %>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

发生的事情是,您没有告诉fields_for它正在执行nested_attributes_for的对象。

使用外部form_for对象的名称前缀字段,它应该有效。