joecritch
joecritch

Reputation: 1105

Save belongs_to ID in a form, without using a hidden field?

I am trying to work out the best way to save a belongs_to record ID, whilst creating a new child record. I am currently using a hidden field to retain the parent's ID.

Can you think of a better way to accomplish this save of the parent's ID (without using a hidden field)?

Here'a a snippet of my routes...

resources :kids
resources :parents do
  resources :kids
end

Here's my parent model...

class Parent < ActiveRecord::Base
  has_many :kids
  accepts_nested_attributes_for :kids
end

Here's my kid model...

class Kid < ActiveRecord::Base 
  belongs_to :parent, :autosave => true
end

Here's my view's form when creating a new kid...

<%= form_for(@kid) do |f| %>
%= f.hidden_field :parent_id, :value => @parent.id %>
<%= f.label :title, 'Title' %>
<%= f.submit %>
<% end %>

Which then gets passed to the create (POST) method...

def create
    @kid = Kid.new(params[:kid])
    @parent = Parent.find(@kid.parent_id)
    @kid.save
    # etc...
end

Upvotes: 1

Views: 1721

Answers (3)

HiteshRawal
HiteshRawal

Reputation: 455

Yes Nested resources is one of the good way but in your case you can also use "field_for".

Upvotes: 1

deafgreatdane
deafgreatdane

Reputation: 1201

If you drop the first line of your routes example, to just

resources :parents do
  resources :kids
end

Now you don't have the ambiguity of calling the KidsController without a parent. Your route match behaves like

/parents/:parent_id/kids

Now, in your KidsController, you can do

def create
  @parent = Parent.find(params[:parent_id])
  @parent.kids.create( params[:kid] )
  #...
end

The new kid gets its parent auto assigned when you create it via the has_many collection

Upvotes: 3

Kristian PD
Kristian PD

Reputation: 2695

If you don't want to pass it in as a hidden field, I'd recommend using nested resources, you could keep the parent_id in the URL and have parents/1/kids as your path. Then, in the KidsController, you'll need to load your parent resource and associate it with the Kid

Upvotes: 0

Related Questions