4

I am not sure how to proper create a rails form with nested form. I have followed many tutorial but becoming more confused has in what should it be, singular plurials, controller... Here my models

model/event.rb

  attr_accessible :description :title, :tag_ids, :locations_attributes
  has_many :location
  accepts_nested_attributes_for :location, :allow_destroy => true

model/location.rb

  attr_accessible :address, :customer_id, :event_id, :latitude, :longitude
  belongs_to :customer
  belongs_to :event

controller.rb

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

view form.html.erb

<%= form_for(@event) do |f| %>
  <%= f.fields_for :locations do |e| %>
    <%= e.text_field :longitude %>
    <%= e.text_field :latitude %>
  <% end %>
  ...
<% end %>

error

Can't mass-assign protected attributes: locations

params send

 "locations"=>{"longitude"=>"45.6666",
 "latitude"=>"47.44444665"},

Either my relationship are wrong because fields_for doesn't support it, either my controller is not proper, or either rails is just not a great language, or i don't understand it anymore.

2
  • You should at least understand that Rails is not a language, it is a framework. Commented Jan 5, 2013 at 20:50
  • Yeah sorry, i agreed its a framework Commented Jan 5, 2013 at 20:54

2 Answers 2

2

You.re nearly there...

event.rb - locations NOT location

attr_accessible :description :title, :tag_ids, :locations_attributes
has_many :locations
accepts_nested_attributes_for :locations, :allow_destroy => true

Should do it I think

edit

And as Valery Kvon says, you need to add

@event.locations.build

to your controller

Sign up to request clarification or add additional context in comments.

1 Comment

By doing this my field for locations don't appear on the form!
1

Edward's answer +

def new
  @event = Event.new
  @event.locations.build
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.