1

I've got a few problems with an attr_accessor when using a form_tag in one my views.

<%= form_tag set_location_locations_path, :method => "post" do %>
  <%= collection_select(:location, :location_id, Location.all, :id, :location_name) %>
  <%= submit_tag "Go" %>
<% end %>

And in my location model I have this:

 attr_accessor :location, :location_id 

And I've also tried attr_writer for good measure.

When I submit the form, I can see this in my console:

  ActionView::Template::Error (undefined method `location_id' for "1":String):

And the post looks like this:

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"oY+jSCV9Mz9iVJnJItADnHdpGhct5DhKpQ+w6JUvgNQ=", "location"=>{"location_id"=>"1"}, "commit"=>"Go"}

I can't figure out why this doesn't work? Previously I've used attr_accessor without problems. Is there something I'm missing?

---- EDIT ----

Controller (not much there)

def set_location
  @location = params[:location][:location_id]      
end

View not much here either:

 = @location
4

1 回答 1

0

您的 collection_select 需要一个具有方法 location_id 的 Location 实例。您正在分配'1'给您的 @location 变量,因此它会尝试'1'.location_id并抱怨。将您的 set_location 方法更改为:

def set_location
  @location = Location.new(params[:location])
end
于 2012-08-14T16:19:30.310 回答