这个多态关联是否设置正确?

时间:2018-06-29 15:44:39

标签: ruby-on-rails polymorphic-associations

我有两种帐户类型,下面的模型中列出了下面的关系。我需要为@account构建一个注册表单,该表单具有一个表单选择字段,用户可以在其中选择注册学生或合作伙伴帐户,并根据选择将该帐户记录保存(即保存到学生或合作伙伴表中,帐户表)。

我在控制器Accounts#new方法上遇到了问题,我不确定如何以一种可行的方式进行设置。

帐户:

  class Account < ApplicationRecord
    belongs_to :acct_holderable, :polymorphic => true

学生:

  class Student < ApplicationRecord
    has_one :account, :as => :acct_holderable

合作伙伴:

  class Partner < ApplicationRecord
    has_one :account, :as => :acct_holderable

查看帐户#new

<%= form_for(@account) do |f| %>
  <%= render 'shared/error_messages', object: @account %>

  <%= f.label :account_type %>
  <%= f.select :acct_holderable, options_for_select(account_type, @account.account_holderable_type), class: 'form-control' %>

 <%= f.label :first_name %>
  <%= f.text_field :first_name, class: 'form-control' %>

  <%= f.label :last_name %>
 <%= f.text_field :last_name, class: 'form-control' %>

  <%= f.label :email %>
  <%= f.email_field :email, class: 'form-control' %>

  <%= f.label :password %>
  <%= f.password_field :password, class: 'form-control' %>

  <%= f.label :password_confirmation %>
  <%= f.password_field :password_confirmation, class: 'form-control' %>

  <%= f.submit yield(:button_text), class: "btn btn-primary" %>
<% end %>

帐户帮助程序(用于options_select)

def account_type
    input =<<-OPTIONS
    Student,
    Partner,
    Other Account TBU,
    Other Account TBU      
    input.split(',')
end

帐户管理员

def new
    @account = Account.new
  end

  def create
    @account = Account.new(account_params)
    if @account.save
      @account.send_activation_email
      flash[:info] = "Please check your email to activate your account before logging in!"
      redirect_to login_url
    else
      render 'new'
    end
  end

1 个答案:

答案 0 :(得分:0)

请检查以下链接以获取更多信息http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

https://6ftdan.com/allyourdev/2015/02/10/rails-polymorphic-models/

这些链接可帮助您更好地了解多态关联。