views:

56

answers:

1

Hello,

In rails, is it possible to pass arguments in when making a new object, and set some values accordingly?

For example, if I have a screen with a list of items, and a link to make a new item at the top. If I were to put a drop-down list of "item types" beside the "new" link, how would I pass that value to the new function on the items controller and have it set @item.item_type?


Edit after the reply from JC below

If in the controller I have the following:

@entry = Entry.new

if (params[:type])
  @entry.entry_type = params[:type]
end

And the link to make a new object is

<%= link_to "Make new article", {:controller => '/dashboard/entries', :action => :new}, :type => 1 %>

then shouldn't the entry_type field in the new.html.erb form get set to 1?

+2  A: 

What you are describing is simply a standard form for a controller's new action and a corresponding create action to receive the form data and create the object. You can generate scaffold files to see an example of how it works, but in a nutshell, it's like this (assuming a RESTful design):

# new.html.erb
<% form_for @item || Item.new do |f| %>
  <%= f.select :type, { 'type1' => 1, 'type2' => 2 } %>
  <%= f.submit %>
<% end %>

# ItemsController#create
@item = Item.new(params[:item])
if @item.save
  redirect_to @item
else
  render :new
end

The data from your form is available in the params hash in the controller and is used to initialize the new object.

Jimmy Cuadra
I was writing a similar answer. That's right, it's an absolutely standard select in a form. Only a detail in your code: instead of writing Item.new it's better to use @item (which comes from the controller), this way a render :new from action create will keep the user previous values.
tokland
hi there, I still don't understand how the new object can pick up the passed in value. I added extra explanations to the original post so show what I'm trying
nktokyo
@tokland - You are right. I will update my code to show what I actually do in my templates. Initially I was just giving a really bare bones version.
Jimmy Cuadra
@ntokyo - I think you're using `link_to` incorrectly. This is probably what you want: `<%= link_to "Make new article", {:controller => '/dashboard/entries', :action => :new, :type => 1} %>`. As it is, you're putting a "type" attribute on the HTML link element and not actually passing the value in the query string.
Jimmy Cuadra
thanks, that did the trick.
nktokyo