简体   繁体   中英

nested form no method error

I have a nested model form giving me a no method error and I can't seem to figure it out. Any help would be greatly appreciated. I'm creating a location and a user in the same form.

The error

NoMethodError in Devise/registrations#new

/app/views/devise/registrations/new.html.erb where line #15 raised:

undefined method `build_location' for #<User:0x007fbafe371188>
Extracted source (around line #15):

12:   <a class="add" href="http://www.google.com/placesforbusiness">Location not available? Click here to add it.</a>
13:   
14:  <!-- form for location info -->
15: <% resource.build_location %>
16: <%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:class => 'form-vertical' }) do |f| %>
17:  <%= f.error_notification %>
18:  <%= f.fields_for :location do |location_form| %>

Location model

class Location < ActiveRecord::Base
  has_and_belongs_to_many :users
  accepts_nested_attributes_for :users, :allow_destroy => true
  attr_accessible :lat, :long, :name, :street_address, :places_id, :users_attributes
  validates_uniqueness_of :places_id, :message => "location already taken"
  resourcify
end

Location controller

def new
    @location = Location.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @location }
    end
  end

  # GET /locations/1/edit
  def edit
    @location = Location.find(params[:id])
  end

  # POST /locations
  # POST /locations.json
  def create
    @location = @user.location.build(params[:location])
    respond_to do |format|
      if @location.save
        format.html { redirect_to @location, notice: 'Location was successfully created.' }
        format.json { render json: @location, status: :created, location: @location }
      else
        format.html { render action: "new" }
        format.json { render json: @location.errors, status: :unprocessable_entity }
      end
    end
  end

What does your User model look like? The model.build_association method is given to you when you declare that a model has_one or belongs_to another model. When you use has_and_belongs_to_many or has_many , you get a model.associations.build (note the pluralization on the associated model).

So depending on what you've got in your User model, you should either have a @user.locations.build method or a @user.build_location method available. Since Rails is complaining about there not being a build_location method on your User model, I'm assuming you're missing an association.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM