本文介绍了在HABTM Rails的嵌套形式:如何prevent重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个表在DB和多到多的关系简单的应用程序。

I have simple app with 3 tables in DB and 'many-to-many' relationships.

# Model Employee
class Employee < ActiveRecord::Base
   has_and_belongs_to_many :phonenumbers
   accepts_nested_attributes_for :phonenumbers, :allow_destroy => true
   attr_accessible :last_name, :first_name, :middle_name, :phonenumbers_attributes
end

# Model Phonenumber
class Phonenumber < ActiveRecord::Base
  has_and_belongs_to_many :employees
  attr_accessible :number
  accepts_nested_attributes_for :employees
end

我有'employees_phonenumbers加入表与雇员标识和phonenumber_id栏目。

I have 'employees_phonenumbers' join-table with 'employee_id' and 'phonenumber_id' columns.

# View
<%= form_for @employee, :url => { :action => :create } do |f| %>

<%= f.label "Last name"   %>
<%= f.text_field :last_name   %>

<%= f.label "First name"   %>
<%= f.text_field :first_name  %>

<%= f.label "Middle name"   %>
<%= f.text_field :middle_name %>

<%= f.fields_for :phonenumbers do |phonenumber| %>
    <%= phonenumber.label "Phone number" %>
    <%= phonenumber.telephone_field :number %>
<% end %>

<%= f.submit "Create" %>
<% end %>

# Controller
def create
  @employee = Employee.new(params[:employee])
  @employee.save ? (redirect_to :action => :index) : (render "new")
end

现在,如果我创建一个用户:约翰与电话号码555,这是确定

Now if I create a user: 'John' with phone number '555', it's OK.

但是,如果我想创建一个用户拉里具有相同的电话号码555,还有在DB555项目。

But if I want to create a user 'Larry' with the same phone number '555', there's a dublicate of '555' entry in the DB.

我如何prevent呢?

How do I prevent this?

更新:我的逻辑是:如果有数字555,那么不要创建一个新的,使用现有的。如果没有这样的一个号码,然后创建一个新的,并使用它。

UPDATE: My logic is: If there is number '555', then do not create a new one, use existing. If there is no such a number, then create a new one and use it.

推荐答案

在employee.rb:

in employee.rb:

before_save :get_phonenumbers


  def get_phonenumbers
    self.phonenumbers = self.phonenumbers.collect do |phonenumber|
      Phonenumber.find_or_create_by_number(phonenumber.number)
    end
  end

我已经找到了工作。

I have found its working

这篇关于在HABTM Rails的嵌套形式:如何prevent重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 01:20