在rails3中创建新记录之前如何检查记录是否存在?

2024-04-14

这就是我想要实现的目标:

  • 我有一个标签系统。
  • 创建帖子时会创建标签(帖子 has_many :tags, :through => :tag_joins.
  • 当使用标签创建帖子时,会自动创建标签连接)。

我想检查该标签是否已经存在。如果是这样,我想使用 tag_join 记录的现有标签,而不是创建新的标签记录。

这是我当前的代码,它不起作用。

class Tag < ActiveRecord :: Base
  belongs_to :user
  belongs_to :tag_join
  belongs_to :post

  before_create :check_exists

  def check_exists
    tag = Tag.where(:name => self.name, :user_id => current_user.id)
    if tag.nil?
      tag = Tag.create(:name => self.name, :user_id => current_user.id)
    end
  end

end

但这不起作用,我在创建任务时收到错误...(服务器实际上只是超时 - 我没有收到特定错误)。

有任何想法吗?

Tokland 说我通过告诉它再次创建标签来创建无限循环 - 所以我尝试了这个:

 def check_exists
      tag = Tag.find_by_name_and_user_id(:name => self.name, :user_id => current_user.id)
      if tag != nil
        self.id = tag.id
      end
  end

并且仍然得到服务器超时

编辑:我不确定这是否重要,但添加标签的方式类似于“http://railscasts.com/episodes/73-complex-forms-part-1

它们嵌套在帖子表单中,并使用如下内容:

def tag_attributes=(tag_attributes)
  tag_attributes.each do |attributes|
    tags.build(attributes)
  end
end

我想知道这是否会阻止整个事情的进行?另外,在模型中使用 current_user.id 似乎肯定是一个问题......

EDIT:

我已经弄清楚了一些事情: 这必须改变,我们之前使用的格式是不正确的语法 - 通常用于 .where 方法。

  def check_exists
     @tag = Tag.find_by_name_and_user_id(self.name, self.user_id) 
     if @tag != nil
       #return false
       #self=@tag
     end
  end

现在的问题是,我可以知道标签是否已经存在。但然后呢?如果我使用 return false 选项,则创建后会出现错误,并且不会创建连接记录...另一个选项“self=@tag”显然不起作用。


您会发现很难从标签模型中做到这一点。看来您想要的是使用嵌套属性更新帖子,如下所示:

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

通过使用虚拟属性设置器方法,这实际上非常简单:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在rails3中创建新记录之前如何检查记录是否存在? 的相关文章

随机推荐