nktokyo
nktokyo

Reputation: 662

rails, pass arguments in when setting a new object

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?

Upvotes: 1

Views: 3927

Answers (1)

Jimmy
Jimmy

Reputation: 37101

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.

Upvotes: 3

Related Questions