开发者

belongs_to parent form with has_many nested form in Rails 3

Abbreviated models:

class Event < ActiveRecord::Base
  belongs_to :place
  accepts_nested_attributes_for :place  
end

class Place < ActiveRecord::Base
  has_many :events  
end

Abbreviated events controller:

  def new
    @event = Event.new
    @event.build_place

  def create
    @event = Event.new(params[:event])

    respond_to do |format|
      if @event.save

Abbreviated view:

<%= form_for(@event) do |f| %>
<%= fields_for @event.place do |place_f| %>

Given the above... I want a user to be able to create an event. When they create the event, they have the option of adding a place. The place may or may not exist in the database.

Right now, the place isn't associated or created on form submission, 开发者_如何学编程but it is definitely in the post parameters.

Any thoughts on what I'm doing wrong? This is for Rails 3.


If you dont want to let user fill place attributes, remove @event.build_place from your new action in controller like this

def new
  @event = Event.new
end

and remove <%= fields_for @event.place do |place_f| %> block from your view.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜