1
我有一个标签模型只有一个属性::name
。自动忽略具有相同属性的重复实例(保存前)?
tag.rb:
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :posts, :through => :taggings
has_many :subscriptions
has_many :subscribed_users, :source => :user, :through => :subscriptions
end
(它有一个后模型many-to-many
关系):
class Post < ActiveRecord::Base
attr_accessible :title, :content, :tag_names
validates :title, :presence => true,
:length => { :maximum => 30 },
:uniqueness => true
validates :content, :presence => true,
:uniqueness => true
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
attr_writer :tag_names
after_save :assign_tags
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
private
def assign_tags
if @tag_names
self.tags = @tag_names.split(" ").map do |name|
Tag.find_or_create_by_name(name)
end
end
end
end
正如你可以想像,我不希望有2具有相同名称的标签。现在,可以创建它们。如果有像这样的标签:<Tag id=1, name=food>
并且以后会创建另一个此类标签:<Tag id=2, name=food>
。我希望第二个被忽略,因为已经有一个名字食物的标签。
(几乎所有的标签系统是如何工作的)
任何建议,为了做到这一点?
对不起,我忘了让我的问题的代码部分可见。 – alexchenco 2012-03-03 08:56:14
请再次检查我的问题。 – alexchenco 2012-03-03 09:04:43
嘿,谢谢,我认为它的工作。你能解释一下你添加的代码是干什么的吗?它似乎忽略了现有的标签,但它是如何知道它们具有相同的名称? – alexchenco 2012-03-03 09:13:42