How do I tell an object it is invalid?

Hi,

How do I tell an object that it is not valid? My model is

class EcOrder < ActiveRecord::Base
has_many :ec_line_items
validates_associated :ec_line_items

end

and in addition to the above, I want the model to only be valid is it
has one or more valid :ec_line_items. So when creating it, can I set
its status to invalid if I don’t detect it has been assigned multiple
child line_items?

              @ec_order = EcOrder.new(params[:ec_order])
#  See if it has line items and if not, set status to

invalid.
if (!@ec_order.valid?)
# Do something
}

Thanks for your thoughts and ideas, - Dave

Hi Dave,

and in addition to the above, I want the model to only be valid is it
has one or more valid :ec_line_items. So when creating it, can I set
its status to invalid if I don’t detect it has been assigned multiple
child line_items?

You can write a custom validation in the model:

def validate
errors.add(:ec_line_items, “is empty”) if ec_line_items.empty?
end


Roderick van Domburg

Hey Roderick, Thanks. This works great. One follow up I have is I
notice when I’m redirected back to the original view because my model
failed validation I have this line

<% error_messages_for :ec_order %>

but nothing gets printed out. Here’s the action in the controller

    def summary
            # Get the subscriber corresponding to the client.
            params[:ec_order][:user_id] = session[:user_id]
            @user = User.find(session[:user_id])
            params[:ec_order][:subscriber_id] = @user.user_id
            @ec_order = EcOrder.new(params[:ec_order])
            if (params[:form] != nil)
                    for form_item_id in params[:form][:form_items]
                            @form_item =

FormItem.find(form_item_id)

@ec_order.ec_line_items.build(:form_item_id => form_item_id,
:description
=> @form_item.description,
:day_supply
=> @form_item.day_supply,
:prescription_number
=> @form_item.prescription_number)
end
end
if (!@ec_order.valid?)
@form = Form.find_by_user_id(@user.id)
render :action => ‘new’
else
session[:ec_order] = @ec_order
end
end

Not sure if I needed to do anything extra with the method you gave me,
but I thought adding to the “errors” was the way to go. Thanks again
for your help, - Dave

On Aug 13, 11:23 am, Roderick van Domburg <rails-mailing-l…@andreas-