开发者

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

开发者 https://www.devze.com 2023-04-08 19:01 出处:网络
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.

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 mo开发者_如何学Cdel...

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


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消