Note that there are some explanatory texts on larger screens.

plurals
  1. PORails nested form on HABTM: how to prevent duplicate entry?
    text
    copied!<p>I have simple app with 3 tables in DB and 'many-to-many' relationships.</p> <pre><code># Model Employee class Employee &lt; ActiveRecord::Base has_and_belongs_to_many :phonenumbers accepts_nested_attributes_for :phonenumbers, :allow_destroy =&gt; true attr_accessible :last_name, :first_name, :middle_name, :phonenumbers_attributes end # Model Phonenumber class Phonenumber &lt; ActiveRecord::Base has_and_belongs_to_many :employees attr_accessible :number accepts_nested_attributes_for :employees end </code></pre> <p>I have 'employees_phonenumbers' join-table with 'employee_id' and 'phonenumber_id' columns.</p> <pre><code># View &lt;%= form_for @employee, :url =&gt; { :action =&gt; :create } do |f| %&gt; &lt;%= f.label "Last name" %&gt; &lt;%= f.text_field :last_name %&gt; &lt;%= f.label "First name" %&gt; &lt;%= f.text_field :first_name %&gt; &lt;%= f.label "Middle name" %&gt; &lt;%= f.text_field :middle_name %&gt; &lt;%= f.fields_for :phonenumbers do |phonenumber| %&gt; &lt;%= phonenumber.label "Phone number" %&gt; &lt;%= phonenumber.telephone_field :number %&gt; &lt;% end %&gt; &lt;%= f.submit "Create" %&gt; &lt;% end %&gt; # Controller def create @employee = Employee.new(params[:employee]) @employee.save ? (redirect_to :action =&gt; :index) : (render "new") end </code></pre> <p>Now if I create a user: 'John' with phone number '555', it's OK.</p> <p>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.</p> <p>How do I prevent this?</p> <p><strong>UPDATE:</strong> 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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload