【发布时间】:2016-03-06 04:07:17
【问题描述】:
尝试使创建用户时,根据他们选择是学生还是公司,rails 将创建该用户学生个人资料或公司个人资料。
我尝试使用多态关联进行设置,但无法弄清楚如何根据视图中选择的内容在模型层生成配置文件。
模型
class User < ActiveRecord::Base
has_secure_password
has_one :student_profile, dependent: :destroy
has_one :corporate_profile, dependent: :destroy
has_many :searches, dependent: :destroy
#attr_accessor :profile_type - removed due to Rails 4, pushed strong params in controller
before_create :create_profile
def create_profile
if profile_type == 1
build_student_profile
else
build_corporate_profile
end
end
end
学生和公司简介
class CorporateProfile < ActiveRecord::Base # or possibly inherit from ActiveRecord::Base if not using inheritance
belongs_to :user
end
class StudentProfile < ActiveRecord::Base # or possibly inherit from ActiveRecord::Base if not using inheritance
belongs_to :user
end
查看
这里我有两个单选按钮来决定注册表单上的用户类型
<%= bootstrap_form_for(@user) do |f| %>
<div class="field">
<%= f.form_group :gender, label: { text: "Gender" }, help: "Are you a corporate or a student?" do %>
<p></p>
<%= f.radio_button :profileable, 1, label: "Student", inline: true %>
<%= f.radio_button :profileable, 2, label: "Corporate", inline: true %>
<% end %>
</div>
用户控制器
class UsersController < ApplicationController
def index
@users = User.paginate(page: params[:page], :per_page => 5).includes(:profile)
end
def show
if params[:id]
@user = User.find(params[:id])
# .includes(:profile)
else
@user = current_user
end
@searches = Search.where(user_id: @user).includes(:state, city: [:profile])
end
def new
@user = User.new
#@corporateprofile = Corporateprofile.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to widgets_index_path
else
redirect to '/signup'
end
end
private
def user_params
params.require(:user).permit(:firstname, :lastname, :email, :password, :profile_type)
end
end
并且控制器上没有传递代码(因为我坚持这样做)。任何更好的建议或解决此问题的方法将不胜感激!
干杯
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 polymorphic-associations