Ruby on rails Rails-已保存多个直通关系而不保存父级
我正在使用Rails 4.2,最近在我的模型中尝试使用has_many through relationship。我在更新记录时遇到了一个问题,不知道如何处理它。 下面是我的模型Ruby on rails Rails-已保存多个直通关系而不保存父级,ruby-on-rails,ruby,rails-activerecord,Ruby On Rails,Ruby,Rails Activerecord,我正在使用Rails 4.2,最近在我的模型中尝试使用has_many through relationship。我在更新记录时遇到了一个问题,不知道如何处理它。 下面是我的模型 class Post < ActiveRecord::Base attr_accessor: name validates :name, :presence => true has_many :post_tags has_many :tags, :through => :post_t
class Post < ActiveRecord::Base
attr_accessor: name
validates :name, :presence => true
has_many :post_tags
has_many :tags, :through => :post_tags, :autosave => false
def tags_used
self.tags.collect(&:name).join(',')
end
def tags_used=(list)
self.tags = list.present? ? Tag.where(:name => list.split(/\s*,\s*/)) : [ ]
end
end
class Tag < ActiveRecord::Base
has_many :post_tags
has_many :posts, :through => :post_tags
end
class PostTag < ActiveRecord::Base
belongs_to :post
belongs_to :tag
end
post验证将失败,因为名称不能为nil。但是post_标签记录正在保存
我尝试了您需要在事务中包装此代码:
@post = Post.find(1)
@post.name = nil
@post.transaction do
@post.tags_used = ["rails","ruby"]
raise ActiveRecord::Rollback unless @post.save
# or just @post.save!
end
您可以及时使用事务来保存帖子。 当您使用
self.tags=[TagsCollection]或self.tags谢谢@faron。我会检查交易。但是,当调用
parent.save
时,falseAutosave将对加载的记录调用save
,这有什么用呢。例如post=post.first;post.tags.to_a;post.save
将在每个标签上调用save
。谢谢@edvin。我会检查交易。但是,这又有什么用呢?”
@post = Post.find(1)
@post.name = nil
@post.transaction do
@post.tags_used = ["rails","ruby"]
raise ActiveRecord::Rollback unless @post.save
# or just @post.save!
end