Error_messages_for

I can’t seem to figure out how to validate a few fields some1 please
help me out

model---------
class Record < ActiveRecord::Base
validates_presence_of :sw, :flex
end

controller------------
class RecordController < A;;icationController
def new
@record = Rrecord.new
@product = Product.find(params[‘product_id’])
end

def create
@Record.new(params[‘record’])
if @record.valid?
@record.save
redirect_to :action => ‘show’, :id = @record.product_id
else
render_action ‘new’
end
end
end

view--------------
<%= error_messages_for ‘Record’ %>

<input id=“record_sw” name = “record[sw]”,size = “40” type= “text” value
=" " />
<input id=“record_flex” name = “record[flex]”,size = “40” type= “text”
value =" " />

Now i know the record will save and be created just fine w/out checking
@record.valid?’, but when i do check, it fails (if the field is blank)
and the render_action ‘new’ complains that it is looking for the
“product_id”, which i understand because it is looking for it in the
controller. Why won’t this work, i’ve spent well more time than
allocated on such a small matter, please help!!!

On 7/13/06, Yngwie [email protected] wrote:

class RecordController < A;;icationController
def new
@record = Rrecord.new
@product = Product.find(params[‘product_id’])
end

def create

This line should read
@record = Record.new(params[:record])

  @Record.new(params['record'])
  if @record.valid?
      @record.save
      redirect_to :action => 'show', :id = @record.product_id
  else
      render_action 'new'
  end

end
end

view--------------

The error_messages for looks for an instance variable with the same name
as
the string provided.

eg
<%= error_messages_for “record” %> #=> looks for @record and displays
errors
<%= error_messages_for “my_object” %> #=> looks for @my_object and
displays
errors

Also in your controller your calling for params[:product_id] which, from
your view I’m guessing is not present.

See the name attribute of your hidden field. record[product_id] This
is
what is submitted back to your controller.

you should have
@product = Product.find(params[:record][:product_id])

<%= error_messages_for ‘Record’ %>

Now i know the record will save and be created just fine w/out checking
@record.valid?’, but when i do check, it fails (if the field is blank)

When the save call is made, the object is checked for validity anyway.
You
can use something like
if @object.save
redirect_to …

If it’s not valid, it won’t save

and the render_action ‘new’ complains that it is looking for the

“product_id”, which i understand because it is looking for it in the
controller. Why won’t this work, i’ve spent well more time than
allocated on such a small matter, please help!!!

See above for product_id parameter