【发布时间】:2016-04-11 14:30:09
【问题描述】:
我正在使用 Rails 4.2,最近尝试在我的模型中通过关系使用 has_many。我在更新记录时遇到问题,不知道如何处理。 考虑以下是我的模型
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 = Post.find(1)
@post.name = nil
@post.tags_used = ["rails","ruby"]
@post.save
帖子将无法通过验证,因为名称不能为 nil。但是 post_tag 记录正在被保存。
我尝试了
如何确保post_tag记录只有在post记录被保存的情况下才被保存
【问题讨论】:
标签: ruby-on-rails ruby rails-activerecord