Topic: Passing parameters through a view....

Im trying to pass a parameter from a link, through a view, and back to a controller.

===========

(Client - show.rhtml)
link_to 'New', { :controller => 'note', :action => 'new', :clientid => @client }

(Note - new.rhtml)
Form for note data lives here

(Note - note_controller.rb)

def create
  @note = Note.new(params[:note])
  @note.created_on = Time.now
  ... etc
end

===========

The only way I have been able to make this work is with a hidden form field. So in the note new.rhtml file, I have <%= hidden_field 'note', 'customer_id' %> which gets filled in in the new method.

Is there a way to pass parameters directly through the form/view and to the resulting controller method, or is this the only way to do it?

Re: Passing parameters through a view....

I'm assuming you are doing this in the new action:

def new
  @note = Note.new(:customer_id => params[:clientid])
end

Passing the value around in the hidden field is not the only way, but it is the best way. This way the customer_id automatically gets set in the create action, no need to specify it manually. It also will automatically be sent along if any error occurs and the new.rhtml form is rendered again. Is there a reason you don't like this method?

BTW, the created_on field should be set automatically upon saving, so there's no need to specify it manually.

Last edited by ryanb (2006-11-25 16:41:03)

Railscasts - Free Ruby on Rails Screencasts

Re: Passing parameters through a view....

Its not that I dont like it, its just the only way I could figure out to make it work, and I thought that there must be some uber-elegant way of doing such things in Rails that I was unaware of.

But if someone with 1200+ posts says its the best way to do it, thats good enough for me.

Thanks so much Ryan!

Re: Passing parameters through a view....

For the record, there are two other ways to do this, but neither are as good IMO. One way is to pass the value in the form's URL:

<%= start_form_tag :action => 'create', :clientid => params[:client_id] %>

The other is to store it in a session:

# in new action
session[:clientid] = params[:clientid]

Both of these require you to set the customer_id manually in the create action, so it ends up being more code.

Last edited by ryanb (2006-11-25 17:08:05)

Railscasts - Free Ruby on Rails Screencasts