我有一个像这样链接的用户模型和公司模型:
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 => "user@domain.com" %>
<%= 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
问题是:访问 /users/new 时出现此错误:
undefined method `before_create' for UsersController:Class
怎么了?我检查了, before_create 没有被弃用,我在 Rails 3.2.8 中。这可能是我的create_company
方法很愚蠢,但我不知道为什么......
非常感谢您的帮助!