I have a model Person which can have many Cars and i want to create a nested form to create two records of car at once for which i am using accepts_nested_attributes_for
. Allow to create two car records at once:
- Hatchback
- Sedan
A person with can leave the one or both of the car fields to be blank and i am using allow_blank
to handle that.
Models:
#### Model: Car
class Car < ActiveRecord::Base
belongs_to :person
validates :registration_number, uniqueness: true, allow_blank: true,
format: {with: SOME_REGEX}
validate :both_cars_registration_cant_be_same
def both_cars_registration_cant_be_same
car1 = registration_number if type == 'hatchback'
car2 = registration_number if type == 'sedan'
if car1 == car2
errors.add(:registration_number, "Both number can't be same")
end
end
### Model : Person
class Person < ActiveRecord::Base
has_many :cars
accepts_nested_attributes_for :cars, allow_destroy: true,
reject_if: proc { |attr| attr['registration_number'].blank? }
Controller:
### Controller : Person
class PersonsController < ApplicationController
def new
@person = Person.new
2.times { @person.cars.build }
end
Below is the small snippet of form partial
...
...
### _form.html.erb ###
<%= f.fields_for :cars do |car|
<%= render 'car_form', c: car %>
<% end %>
...
...
### _car_form.html.erb ###
<% if c.index == 0 %>
<p>Type: Sedan</p>
<%= c.hidden_field :type, value: "sedan" %>
<% else %>
<p>Type: Hatchback</p>
<%= c.hidden_field :type, value: "hatchback" %>
<% end %>
<div>
<%= c.label :registration_number %>
<%= c.text_field :registration_number %>
</div>
I can use validate :both_cars_registration_cant_be_same
with valid?
from Cars model in rails console but how do i run this validation from the parent model (person) so that i get the error message when the form is submitted with same registration number for two cars?. I want to validate that the registration number fields entered for two record must be different and not same. Also let me know if my form helper where i am using index
on the fields_for
object is the correct way to do it?
P.S : Using rails 4