2013-01-06 88 views
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 

回答

0

什麼是您的User模型?當您聲明模型has_onebelongs_to另一個模型時,將給予model.build_association方法。當你使用has_and_belongs_to_manyhas_many時,你會得到一個model.associations.build(注意關聯模型的複數形式)。

因此,根據您在User模型中得到的結果,您應該有@user.locations.build方法或@user.build_location方法可用。由於Rails抱怨User模型中沒有build_location方法,我假設你錯過了一個關聯。

+0

謝謝。就是這樣。我需要將其更改爲user.locations.build – jacobt