【问题标题】:Rails HABTM fields_for – check if record with same name already existsRails HABTM fields_for – 检查同名记录是否已经存在
【发布时间】:2010-11-13 12:45:24
【问题描述】:

模型“片段”和“标签”之间存在 HABTM 关系。目前,当我保存带有几个标签的 sn-p 时,每个标签都会保存为新记录。

现在我想检查是否已经存在同名标签,如果是这样,我不想要新记录,只需要 sn-ps_tags 中的条目到现有记录。

我该怎么做?

sn-p.rb:

class Snippet < ActiveRecord::Base
  accepts_nested_attributes_for :tags, :allow_destroy => true, :reject_if => lambda { |a| a.values.all?(&:blank?) }
  ...
end

_sn-p.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 %>

【问题讨论】:

  • 我也坚持这个,期待应该有一个答案,但没有投票,没有最爱,3.5年没有答案(除了作者本人)!?

标签: ruby-on-rails-3 tagging relationship has-and-belongs-to-many


【解决方案1】:

好吧,我很不耐烦……过了一会儿,我找到了一个适合我的解决方案。我不知道这是否是最好的方法,但我想展示它。

我不得不修改 Ryan Bates Railscast "Auto-Complete Association" 的解决方案,该解决方案处理了一个 belongs_to-association 以使其与 HABTM 一起使用。

在我的 sn-p-form 中有一个名为 tag_names 的新文本字段,它需要一个逗号分隔的标签列表。

和 Ryan 一样,我使用虚拟属性来获取和设置标签。我认为其余部分是不言自明的,所以这里是代码。

查看“_sn-p.html.erb”

<div class="float tags">
  <%= f.label :tag_names, "Tags" %>
  <%= f.text_field :tag_names %>
</div>

型号“sn-p.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

这只是基本代码,没有经过很好的测试,需要改进,但它似乎有效,我很高兴有一个解决方案!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多