1

我有一个嵌套模型表单给我一个无方法错误,我似乎无法弄清楚。任何帮助将不胜感激。我正在以相同的形式创建一个位置和一个用户。

错误

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| %>

位置模型

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

位置控制器

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
4

1 回答 1

0

你的User模型是什么样的?model.build_association当您声明一个模型has_onebelongs_to另一个模型时,该方法会提供给您。当您使用has_and_belongs_to_manyorhas_many时,您会得到一个model.associations.build(注意相关模型上的复数形式)。

因此,根据您的User模型中的内容,您应该有一个@user.locations.build方法或一个@user.build_location可用的方法。由于 Rails 抱怨build_location您的模型上没有方法User,我假设您缺少关联。

于 2013-01-06T05:25:16.853 回答