gpt4 book ai didi

nested - Rails 4,嵌套属性,对于ID ==的人找不到ID =的标签

转载 作者:行者123 更新时间:2023-12-04 20:47:14 24 4
gpt4 key购买 nike

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

我的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'}])

Couldn't find Tag with ID=15 for Person with ID=



请告诉我该怎么做才能保留模型

最佳答案

我遇到了同样的问题。我认为Rails只是不支持使用现有的嵌套记录创建新记录。对于这种情况,我没有找到任何解决方案。
因此,尝试从person_params过滤tag_attributes,然后使用tag_ids如下:

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

关于nested - Rails 4,嵌套属性,对于ID ==的人找不到ID =的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18835422/

24 4 0