【问题标题】:Is this polymorphic association being set up correctly?这种多态关联是否设置正确?
【发布时间】:2018-06-29 15:44:39
【问题描述】:

我有两种帐户类型,下面的模型中列出了以下关系。我需要为@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

【问题讨论】:

  • 您在Accounts#new 中遇到了什么问题?你有错误吗?

标签: ruby-on-rails polymorphic-associations


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2016-08-20
    • 1970-01-01
    相关资源
    最近更新 更多