无法在Rails 4中检索attr_accessor

时间:2014-06-15 14:04:17

标签: ruby-on-rails ruby callback

我正在开发Ruby on Rails项目,我有两个模型:

1。用户

2。商户

他们的关系是:

用户has_one:商家

商家belongs_to:用户

然后在我的 user.rb

attr_accessor :merchant_name
after_create :create_merchant

def create_merchant
  create_merchant(name: merchant_name)
end

以我的用户形式:

= form_for @user do |f|
  = f.text_field :merchant_name
  = f.text_field :email
  = f.text_field :password

问题是用户和商家已创建,但商家名称为零

在我的帐户:: RegistrationsController

class Account::RegistrationsController < Devise::RegistrationsController

  protected
  def after_sign_up_path_for(resource)
    account_users_path
  end


  private

  def registration_params
    params.require(:user).permit(:merchant_name)
  end

end

我收到此错误:

  Processing by Account::RegistrationsController#create as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"ht8vHG8I4bz2ylt+mtLC7hilQnK3VnYtcHgSNv8nSeg=", "user"=>{"merchant_name"=>"Zara 123", "email"=>"allen.chun@hotmail.com", 
"password"=>"[FILTERED]", 
"password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign Up"}

    Unpermitted parameters: merchant_name

2 个答案:

答案 0 :(得分:3)

也许应该是

attr_accessor :merchant_name
after_create :create_merchant

def create_merchant
  build_merchant(name: merchant_name)
  save
end

create_association hasn't supported in rails 4

另请不要忘记to permit merchant_name。根据这个信息:

class Account::RegistrationsController < Devise::RegistrationsController

  before_action :configure_permitted_parameters

  protected
  def after_sign_up_path_for(resource)
    account_users_path
  end

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :merchant_name
  end
end

答案 1 :(得分:3)

如果我是你,我不会覆盖create_merchant方法,尝试这样的事情:

after_create -> { create_merchant!(:name => self.merchant_name) }

并确保在用户控制器中允许您的merchant_name,如下所示:

def create
  @user = User.new(user_params)
  if @user.save
    redirect_to @user
  else
    render :new
  end
end

private

def user_params
  params.require(:user).permit(:merchant_name, :email, :password, :password_confirmation)
end