Chris
(Chris)
September 16, 2007, 12:50pm
#1
What would be considered the "standard" way of setting the foreign key
on a child record when starting from a view of the parent record? E.g.
you're on a view to a person record and use a link_to load a form that
will enable you to add an address for that person (addresses are
stored in a separate table):
<%= link_to 'New address', { :controller => 'addresses', :action =>
'new' } %>
The create action in the addresses controller needs to set the
person_id.
Thanks for your input.
One way is to add person_id to the link to the address construction form:
<%= link_to 'New address', { :controller => 'addresses', :action
=>'new', :person_id => person } %>
Then pass the person_id to the address construction view and store it in
a hidden field
then in the create method:
@person = Person.find(params[:person_id])
@person.create_address (params[:address])
Chris Bartlett wrote:
Chris
(Chris)
September 17, 2007, 7:54am
#3
Thanks for the pointer. I'd looked around and couldn't find a clear
example. Here's the relevant code in the various files I used to get
this working.
views/people/show.rhtml
<%= link_to 'New address', { :controller => 'addresses', :action =>
'new', :person_id => @person } %>
views/addresses/new.rhtml
<% form_for :address, :url => { :action => :create } do |form| %>
<%= form.hidden_field :person_id, :value => params[:person_id] %>
[... other form fields, save button, etc.]
<% end %>
models/person.rb
class Person < ActiveRecord::Base
has_many :addresses
end
models/address.rb
class Address < ActiveRecord::Base
belongs_to :person
# So the addresses table needs a 'person_id' column, which is the
foreign key
end
controllers/addresses_controller.rb
def new
@address = Address.new
end
def create
@address = Address.new(params[:address])
[...]
end