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
方法愚蠢,但我不明白为什么...
非常感谢您的帮助!
谢谢!我以前认为_是一个选择器。例如before_index,before_show都可以。 所以我改变了这一点,我现在没有这个错误信息。 before_filter:create_company,:only =>:create –
太棒了!你做得很好〜这就是铁轨的工作方式〜 –