简体   繁体   English

具有嵌套属性和多态关联的Authlogic

[英]Authlogic with nested attributes and polymorphic associations

I'm having trouble with the following code: 我在使用以下代码时遇到麻烦:

User < AR
  acts_as_authentic

  belongs_to :owner, :polymorphic => true
end

Worker < AR
  has_one :user, :as => :owner
  accepts_nested_attributes_for :user
end

Employer < AR
  has_one :user, :as => :owner
  accepts_nested_attributes_for :user
end

I'd like to create registration forms based on user types, and to include authentication fields such as username and password. 我想根据用户类型创建注册表单,并包括身份验证字段,例如用户名和密码。 I currently do this: 我目前正在这样做:

UserRegistrationController < AC
  #i.e. a new Employer
  def new
    @employer = Employer.new
    @employer.build_user
  end
...
end

I then include User fields with fields_for . 然后,我在“ fields_for包含“用户”字段。 All views render fine, but here's the catch: I cannot build a User, it tells me :password is a wrong method, so I guess the authentication logic has been bypassed. 所有视图都可以正常渲染,但是这里有个要点:我无法建立一个User,它告诉我:password是错误的方法,所以我猜想身份验证逻辑已被绕过。 What should I do? 我该怎么办? Am I doing it wrong altogether? 我完全做错了吗? Should I drop polymorphic associations in favor of Single Table Inheritance? 我应该放弃多态关联以支持单表继承吗? Whatever I do, I have to make sure it plays nicely with Authlogic. 无论我做什么,我都必须确保它与Authlogic配合良好。

I'd approach the building of new users of either type in the opposite direction. 我会朝相反的方向发展这两种类型的新用户。 ie: 即:

#controller 
@employer = Employer.new
@user = @employer.build_user

#view
form_for @user |f|
  f.text_field :login
  f.password_field :password
  fields_for :owner, @employer |f_e|
    f_e.some_field :some_value

#controller
def create
  @owner = params[:owner][:some_employer_field_or_virtual_attribute] ? Employer.new params[:owner] : Worker.new params[:owner]
  @owner.save
  @user = User.new(params[:user].merge!(:owner => @owner)
  if @user.save
    ...

re. 回覆。 mentioned virtual attribute - if there's no field in the model, and thus in the form, which distinguishes user type as employer or worker then set an virtual attribute within each which you can put as a hidden boolean field in the form 提到的虚拟属性-如果模型中没有字段,因此在表单中没有将用户类型区分为雇主或工人的形式,则在其中设置一个虚拟属性,您可以将其作为表单中的隐藏布尔字段放置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM