9

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

我的人员控制器:

  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 的标签

请告诉我如何保存模型

4

2 回答 2

2

我遇到了同样的问题。我认为 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 })
于 2013-11-08T16:20:49.397 回答
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如何创建一个人,你必须发送一个标签对象或创建它或两者兼而有之

于 2020-08-20T14:13:11.410 回答