Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails-已保存多个直通关系而不保存父级_Ruby On Rails_Ruby_Rails Activerecord - Fatal编程技术网

Ruby on rails Rails-已保存多个直通关系而不保存父级

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

我正在使用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_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