开发者

updating nested attributes fails because uniqueness validation fails

Here are the associations and the relevant depende开发者_StackOverflow中文版ncies and validation

The post model: Post has_many :post_tags Post has_many :tags, :through => :post_tags

The tag model: validates :content, :uniqueness => true

the problem is this: when I want to assign a tag to a post (i.e. post.tags << new_tag), the operation fails if a tag with the same content already exists in the database, because of the uniqueness validations failing.

the desired behavior would be this: when assigning a new tag to a post - if the tag already exists then do not try to create a new tag, rather only create the post_tag relation. This will avoid the uniqueness validation failure, but still assign the tag to the post

  • if the tag does not exists, then create a new tag and also a post_tag relation.

What would be a clean way to do this? Thanks,

-p.s. Two methods I'm pondering are doing the association creations by hand, ie not using the nested attributes feature. Or overriding AvtiveRecords's 'autosave_associated_records_for_tags' method in the UserPost model, which handles the autosaving of associated models (in this case tags), and modifying it to do a check for existence of the tag before trying to save it


user find_or_create_by_{attr}

http://api.rubyonrails.org/classes/ActiveRecord/Base.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜