Rails 4,嵌套属性,无法找到ID为ID的ID =

时间:2013-09-16 19:07:39

标签: nested ruby-on-rails-4 strong-parameters

Rails 4: 我想创建带标签的人

person = Person.new(:name=>Jon', :tags_attributes=>[{:id=>'15', :name=>'some_tag'}])

我的人物型号:

class Person < ActiveRecord::Base

  validates :name, presence: true

  belongs_to :user
  has_many :organizations, through: :people_organizations
  has_and_belongs_to_many :tags, join_table: :people_tags

  has_many :phones, as: :phoneable, :dependent => :destroy
  has_many :emails, as: :emaileable, :dependent => :destroy
  has_many :networks, as: :networkable, :dependent => :destroy
  has_many :messengers, as: :messengerable, :dependent => :destroy

  accepts_nested_attributes_for :phones, :emails, :networks, :messengers, allow_destroy: true
  accepts_nested_attributes_for :tags, reject_if: :all_blank

end

My PeopleController:

  def create
    @person = Person.new(person_params)

    respond_to do |format|
      if @person.save(validate: false)
        format.json { render action: 'show', status: :created }
      else
        format.json { render json: @person.errors, status: :unprocessable_entity }
      end
    end
  end

  def person_params
    params.require(:person).permit(:id, :name, :born, :description, 
      phones_attributes:[:id, :number, :_destroy],
      emails_attributes:[:id, :email, :_destroy]
      networks_attributes:[:id, :name, :_destroy],
      messengers_attributes:[:id, :identifier, :_destroy],
      tags_attributes:[:id, :name, :_destroy]
    )
  end

当我创建新人时,我有错误

p = Person.new(:name=>'Jon', :tags_attributes=>[{:id=>'15', :name=>'tag'}])
  

对于ID =

的人,找不到ID = 15的标签

请告诉我如何保留模型

2 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。我认为rails只支持使用现有的嵌套记录创建新记录。我根本找不到这种情况的解决方案。 因此,尝试从person_params过滤tags_attributes,然后使用tag_ids,如下所示:

tag_ids = params[:person][:tags_attributes].map { |tag| tag[:id] }
@person = Person.new(person_params.merge({ tag_ids: tag_ids })

答案 1 :(得分:0)

您应该通过people_tags关系创建嵌套字段,例如类似的

= form_for(@person) do |f|
  = f.text_field :name
 
  = f.simple_fields_for :people_tags do |people_tag_builder|
    people_tag_builder.hidden_field :tag_id 15
    
    = people_tag_builder.simple_fields_for :tags, user do |tag_builder|
      = tag_builder.id 15
      = tag_builder.text_field :name, value: 'tag'

people_tag_builder.hidden_field :tag_id 15是强制性的,因为它的中间表需要person_idtag_id来创建人,您必须发送标签对象或创建标签对象或同时创建标签对象