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

后端 未结 7 1406
悲哀的现实
悲哀的现实 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:16

    I believe the other answers are a bit dated. Here's how you should probably accomplish this for Rails 4

    tag = Tag.first_or_initialize(:name => self.name, :user_id => current_user.id)
    if !tag.new_record?
        tag.id = self.id
        tag.save
    end
    

提交回复
热议问题