我有一个嵌套的模型表单,给我一个无方法错误,我似乎无法搞清楚。任何帮助将不胜感激。我正以相同的形式创建位置和用户。
错误
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
答案 0 :(得分:0)
您的User
型号是什么样的?当您声明模型model.build_association
或has_one
其他模型时,会向您提供belongs_to
方法。当您使用has_and_belongs_to_many
或has_many
时,您会获得model.associations.build
(请注意相关模型上的复数形式)。
因此,根据您在User
模型中所拥有的内容,您应该使用@user.locations.build
方法或@user.build_location
方法。由于Rails抱怨build_location
模型上没有User
方法,因此我假设您错过了关联。