Rails HABTMfields_for –检查是否存在同名记录 [英] Rails HABTM fields_for – check if record with same name already exists
问题描述
我在模型片段"和标签"之间存在HABTM关系.当前,当我保存带有一些标签的代码片段时,每个标签都另存为新记录.
I have a HABTM-relation between the models "Snippets" and "Tags". Currently, when i save a snippet with a few tags, every tag is saved as a new record.
现在,我要检查是否已存在具有相同名称的标签,如果是这种情况,我不希望有新记录,只需在snippets_tags中添加一个到现有记录的条目即可.
Now i want to check if a tag with the same name already exists and if that´s the case, i don´t want a new record, only an entry in snippets_tags to the existing record.
我该怎么做?
snippet.rb:
snippet.rb:
class Snippet < ActiveRecord::Base
accepts_nested_attributes_for :tags, :allow_destroy => true, :reject_if => lambda { |a| a.values.all?(&:blank?) }
...
end
_snippet.html.erb:
_snippet.html.erb:
<% f.fields_for :tags do |tag_form| %>
<span class="fields">
<%= tag_form.text_field :name, :class => 'tag' %>
<%= tag_form.hidden_field :_destroy %>
</span>
<% end %>
推荐答案
好吧,我很不耐烦……过了一会儿,我找到了适合我的解决方案.我不知道这是否是最好的方法,但是我想展示一下.
Ok, i´m impatient… after a while i found a solution that works for me. I don´t know if this is the best way, but i want to show it though.
我必须修改Ryan Bates Railscast的解决方案自动完成协会" ,它处理一个Emirates_to-association以使其与HABTM一起使用.
I had to modify the solution of Ryan Bates Railscast "Auto-Complete Association", which handles a belongs_to-association to get it working with HABTM.
在我的代码段形式中,是一个名为tag_names的新文本字段,该字段需要逗号分隔的标签列表.
In my snippet-form is a new text field named tag_names, which expects a comma-separated list of tags.
像Ryan一样,我使用虚拟属性来获取和设置标签.我认为其余的内容不言而喻,所以这里是代码.
Like Ryan, i use a virtual attribute to get and set the tags. I think the rest is self-explanatory, so here´s the code.
查看"_snippet.html.erb"
View "_snippet.html.erb"
<div class="float tags">
<%= f.label :tag_names, "Tags" %>
<%= f.text_field :tag_names %>
</div>
模型"snippet.rb":
Model "snippet.rb":
def tag_names
# Get all related Tags as comma-separated list
tag_list = []
tags.each do |tag|
tag_list << tag.name
end
tag_list.join(', ')
end
def tag_names=(names)
# Delete tag-relations
self.tags.delete_all
# Split comma-separated list
names = names.split(', ')
# Run through each tag
names.each do |name|
tag = Tag.find_by_name(name)
if tag
# If the tag already exists, create only join-model
self.tags << tag
else
# New tag, save it and create join-model
tag = self.tags.new(:name => name)
if tag.save
self.tags << tag
end
end
end
end
这只是基本代码,没有经过很好的测试,还需要改进,但是它似乎可行,我很高兴有一个解决方案!
This is just the basic code, not very well tested and in need of improvement, but it seemingly works and i´m happy to have a solution!
这篇关于Rails HABTMfields_for –检查是否存在同名记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!