views:

52

answers:

1

I'm trying to create an accessor for one element from array with specific flag set to true:

class EntranceObject < ActiveRecord::Base
  has_many :subscribers

  def customer
      self.subscribers.find(:first, :conditions => {:is_customer => true})
  end

  def customer=(customer_params)
    self.subscribers << Subscriber.new(:name => customer_params[:name],
                                       :apartment => customer_params[:apartment],
                                       :phone_number => customer_params[:phone_number],
                                       :is_customer => true)
  end
end

class Subscriber < ActiveRecord::Base
  belongs_to :entrance_object

  validates_presence_of :name, :apartment         
end

How do i need to validate this accessor in order to hightlight missing fields in a view?

P.S. I'm newbie in RoR, maybe there is another approach to such work with one element from a collection? Thanks.

A: 

You can have Rails magic do the work for you.

class EntranceObject < ActiveRecord::Base
  has_many :subscribers
  has_one :customer, :class_name => "Subscriber", :foreign_key => "entrance_object_id", :conditions => {:is_customer => true}

  validates_associated :customer
end

The validates_associated will validate the customer object and store the errors in entrance_object.customer.errors (so you will have to do so some work in showing all the errors in the view).

See here for docs on validates_associated.

Tony Fontenot
this is real magic! thanks a lot!(%
memph1s