Use of foreign keys


I am a rails newbie, have a simple question: I have two tables, valor, belongs to an object at the variables table

On the page of a single variable, I put the following link:

<%= link_to 'Novo Valor', :controller => "valors", :action=> 'new', :id=>@variable%>

So the URL appears as: http://localhost:3000/valors/new?id=1

But how do I use the id value represented at the URL in order to create a new valor object with the foreign key variable_id=1?

Something like:

# Your action
def new
  @valor = => params[:id])

# Then in the view:
<%= form_for(@valor) do |f| %>
<% end %>

You could also simplify the action and make it more flexible by passing the full object parameters in the same way create and update works, like:

def new
  @valor =[:valor] || {})

# making your link:
<%= link_to 'Novo Valor', :controller => "valors", :action=> 'new', :valor => { :variable_id => @variable } %>

This makes the generated URL a bit uglier, but would allow you to pass arbitrary creation parameters to the new record, rather than manually building them in the controller.

Side note, given that you're using standard resourceful routes, you could simplify the link generation by using the named route for a new Valor:

<%= link_to 'Novo valor', new_valor_path(:valor => { :variable_id => @variable }) %>