我有一个Rails应用程序。我安装了Devise。我想在User模型和不同的配置文件之间建立多态关联,例如:Student and Mentor。
这就是我要做的事情:让学生注册页面包含常规设计字段,例如:email
,password
,password_confirmation
。但我也希望有专门针对学生档案的字段,例如residency_type
和graduation_year
user.rb
class User < ActiveRecord::Base
belongs_to :profile, polymorphic: true
student_profile.rb
class StudentProfile < ActiveRecord::Base
has_one :user, as: :profile, dependent: :destroy
registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def new_student_registration
resource = build_resource({})
respond_with resource
end
...
我可以在控制台上创建一个带有学生档案的用户,就像这样...
u = User.new
u.email = "something@whatever"
... (password and password confirmation)
u.profile = StudentProfile.new
u.graduation_year = "2014"
u.save
问题是,我无法弄清楚如何设置控制器和表单来做到这一点。我该怎么做?请注意用户与学生档案之间的关系。
答案 0 :(得分:0)
观看此导演剧集http://railscasts.com/episodes/210-customizing-devise
对于配置文件,我认为您只需要在新页面表单中添加字段,并在用户模型中使其接受嵌套属性。要了解配置文件的内容,您可以选择一个框和一个之前的过滤器,以查看基于该值的配置文件
答案 1 :(得分:0)
我最好的建议是覆盖Devise视图和注册控制器,并使用表单对象注册用户。这是表单对象的绝佳资源:http://blog.jasonharrelson.com/blog/2014/04/06/how-i-design-rails-applications-part-2-form-objects/
ActiveModel::Model对于创建表单对象非常有用,尽管有些人喜欢使用某些宝石,例如reform。
我希望有所帮助!