0

I'm trying to make a change to some controller code. But, I don't understand where to put it.

I have the following in a new Contact form:

    <%= f.association :location, :label_method => :name, :label => 'Location:' %>

I assumed that code would execute the index code in the location's controller.

But, I just deleted all of the code in the location index and the Contact form with the association to Location still has data in it.

I want the following code to execute at the Contact association stmt, but I don't know where to put it:

@locations = Location.ordered_by_ancestry_and(:name).map { |l| ["  " * l.depth + l.name, l.id] }

UPDATE1

This is the development.log

Processing by ContactsController#new as HTML
Location Load (0.2ms)  SELECT "locations".* FROM "locations" ORDER BY (case when locations.ancestry is null then 0 else 1 end), locations.ancestry, name

UPDATE2

I changed the ContactsController#new to this for testing:

 # GET /contacts/new
 # GET /contacts/new.json
 def new
   @locations = Location.first

And I still got all the locations in the select box.

4

1 回答 1

0

The SimpleFormFor association helper method will generate a list (as a select list by default, but can be modified to radio or checkbox list) that acts as a nested attribute for that association. When submitted this field will be passed to the same controller action as the parent form - in this case the ContactsController#create action.

As far as your customized list of locations, you can pass this as a collection option to the association method:

<%= f.association :location, :collection => @locations, :label_method => :name, :label => 'Location:' %>

The actual place to build this @locations list would be in any action that may need to access it - that includes new and edit, as well as create and update (in case an error prevents your form from submitting). You can use a before_filter to eliminate any duplication.

The code may look something like:

class ContactsController < ApplicationController
  before_filter :load_locations, :only => [:new, :edit, :create, :update]

  #... actions go here

  private
  def load_locations
    @locations = Location.ordered_by_ancestry_and(:name).map do |l| 
      ["  " * l.depth + l.name, l.id]
    end
  end
end
于 2013-05-06T15:29:36.377 回答