2012-11-22 29 views
2

我有一個用戶模型和公司模型鏈接是這樣的:未定義的方法`before_create」

class User < ActiveRecord::Base 
    belongs_to :company 
    accepts_nested_attributes_for :company 
end 

class Company < ActiveRecord::Base 
    has_many :users 
end 

在登錄頁,我希望用戶建立兩個他的信息(電子郵件,密碼)和他的公司信息(幾個領域)。所以我的形式如下:

<%= simple_form_for @user, :html => { :class => 'form-horizontal' } do |f| %> 

     <%= f.input :email, :required => true, :placeholder => "[email protected]" %> 
     <%= f.input :password, :required => true %> 
     <%= f.input :password_confirmation, :required => true %> 

<h2>Company info</h2> 
<%= simple_fields_for :company, :html => { :class => 'form-horizontal' } do |fa| %> 
    <%= fa.input :name %> 
    <%= fa.input :url %> 
    <%= fa.input :description, :as => :text, :input_html => { :cols => 60, :rows => 3 } %> 
    <%= fa.input :logo %> 
    <%= fa.input :industry %> 
    <%= fa.input :headquarters %> 
<% end %> 

     <div class="form-actions"> 
      <%= f.submit nil, :class => 'btn btn-primary' %> 
      <%= link_to t('.cancel', :default => t("helpers.links.cancel")), 
      root_url, :class => 'btn' %> 
     </div> 

<% end %> 

我的用戶模型具有company_id:integer場。因此,在邏輯上,當我登錄用戶時,首先要做的是在用戶面前創建公司,然後向用戶創建模型提供合適的company_id。所以我寫了這一點:

class UsersController < ApplicationController 
    before_create :create_company 

    def new 
    @user = User.new 
    end 

    def create 
    @user = User.new(params[:user]) 
    if @user.save 
     redirect_to root_url, :notice => "Registration successful." 
    else 
     render :action => 'new' 
    end 
    end 

private 

    def create_company 
    @company = Company.new(params[:company]) 
    if @company.save 
     self.company_id = @company.id 
    else 
     render :action => 'new' 
    end 
    end 

end 

問題是:訪問/用戶/當新我得到這個錯誤:

undefined method `before_create' for UsersController:Class 

什麼錯?我檢查過,before_create沒有被棄用,我在Rails 3.2.8中。這可能是我的create_company方法愚蠢,但我不明白爲什麼...

非常感謝您的幫助!

回答

1

before_create是屬於的ActiveRecord

的before_filter是屬於控制器的鉤方法鉤方法。

所以我建議你在清楚哪個是哪個之後重新構建你的代碼。^_^

+0

謝謝!我以前認爲_是一個選擇器。例如before_index,before_show都可以。 所以我改變了這一點,我現在沒有這個錯誤信息。 before_filter:create_company,:only =>:create –

+0

太棒了!你做得很好〜這就是鐵軌的工作方式〜 –