开发者

Rails 3 Nested Resources Edit/Update Controller

I'm wrapping my head around Nested Resources (awesome btw) and I have a question in regards to the Edit and Update actions in my controller.

My route is set up with the following:

resources :events do
 resources :people
end

In my People controller, I have the following for the New action:

 @event = current_user.events.find(params[:event_id])
 @person = @event.people.build
 @person.build_address

and for the Create action I have:

@event = current_user.events.find(params[:event_id])
@person = @event.people.build(params[:person]) 

This all works great.

I'm unsure of what I need to do for the Edit and Update actions though. Googling hasn't yielded any good links.

Here are my models:

class Event < ActiveRecord::Base
   belongs_to :user
   belongs_to :address
   has_many :people
   accepts_nested_attributes_for :address, :allow_destroy => true
end

class Person < ActiveRecord::Base
  belongs_to :event
  belongs_to :address
  accepts_nested_attributes_for :address, :allow_destroy => true
end

class Address < ActiveRecord::Base
  has_many :people
  has_many :events
end

I basically want to make sure that when I edit a person, AR will update the cor开发者_C百科rect event id and address id along with the person's details.

Thanks!


Your model setup is incorrect. You have a

belongs_to

on either side of the Event-Address and the People-Address relationship. In a one-to-many relationship you need to have a

has_many

on 1 side and a

belongs_to

on the other side.

That apart from your controller's perspective its quite straight-forward to setup your edit and update actions. Its just how you you setup the new and create actions. Here's a Railscast that talks about nested resources.

Note: Helping you with controller code would be easier if you correct your model relationships.

UPDATE

Your model relationships look fine. So now its pretty straightforward. I hope the Railscast that I linked helped you out on nested resources.

Here's another useful resource on Nested Resources.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜