How to check if a record exists before creating a new one in rails3?

后端 未结 7 1405
悲哀的现实
悲哀的现实 2021-02-03 14:36

Heres what I\'m trying to accomplish:

  • I have a tagging system in place.
  • Tags are created, when Posts are created (posts has_many :tags, :through => :tag
7条回答
  •  生来不讨喜
    2021-02-03 15:09

    You're going to find it hard to to this from within the Tag model. It seems like what you want is to update the Post using nested attributes, like so:

    post = Post.create
    post.update_attributes(:tags_attributes=>{"0"=>{:name=>"fish",:user_id=>"37"}})
    

    This is actually pretty simple to do by using a virtual attribute setter method:

    class Post < AR::Base
      has_many :tags
    
      def tags_attributes=(hash)
        hash.each do |sequence,tag_values|
          tags <<  Tag.find_or_create_by_name_and_user_id(tag_values[:name],\
            tag_values[:user_id])
        end
      end
    
    > post = Post.create
    > post.update_attributes(:tags_attributes=>{"0"=>{:name=>"fish",:user_id=>"37"}})
    > Tag.count # => 1
    # updating again does not add dups
    > post.update_attributes(:tags_attributes=>{"0"=>{:name=>"fish",:user_id=>"37"}})
    > Tag.count # => 1
    

提交回复
热议问题