Ruby on rails 带有STI和DEVICE的嵌套形式
关于这个话题有很多问题,但我找不到解决问题的办法 我有一个名为User的designe模型,它(使用单表继承)有一个名为Student的子类(以及其他子类) 学生与名为Vehicle的班级有“has_one”联系 我的模型设置:Ruby on rails 带有STI和DEVICE的嵌套形式,ruby-on-rails,devise,nested,nested-forms,sti,Ruby On Rails,Devise,Nested,Nested Forms,Sti,关于这个话题有很多问题,但我找不到解决问题的办法 我有一个名为User的designe模型,它(使用单表继承)有一个名为Student的子类(以及其他子类) 学生与名为Vehicle的班级有“has_one”联系 我的模型设置: class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
class Student < User
has_one :vehicle, :dependent => :destroy
accepts_nested_attributes_for :vehicle, allow_destroy: true
end
class Vehicle < ActiveRecord::Base
belongs_to :student
end
假设Desive是为用户类设置的,我认为这会创建一个“User”类型的资源,并将其传递给我的视图,而视图则无法将其链接到“Vehicle”
有没有办法创建所需的关联或创建“student”类型的资源以传递到视图 这可能不是答案(如果需要,我会删除),但我会给你我的观察和想法: -- 创建 您当前正在使用
users#注册
作为控制器方法,但您希望填充Student
类
我不知道Desive在这种情况下是如何工作的,但我知道如果您想正确使用STI,最好直接使用本机对象。例如,如果您希望创建学生,最好使用以下方法:
#app/controllers/students_controller.rb
class StudentsController < InheritedResources::Base #-> assuming you wish to use Inherited Resources
def new
new!(@student.build_vehicle)
end
private
def permitted_params
params.permit(:student => :your, :student, :params, vehicle_attributes: [:vehicle, :attributes])
end
end
这将允许您创建一个新的Student
对象(您以前没有创建过该对象)
我不知道这是否适用于Deviate,但我可以肯定的是,如果您按照我上面概述的方式发送请求,您将能够创建一个
Student
对象,从而能够创建所需的功能感谢您的回复。我同意你建议的方法是有效的,即使使用Desive。我可以创建一个学生对象(和相关的车辆对象),但是,问题是Desive功能不需要回复丰富。我同意你建议的方法会奏效,包括Desive。但是,这意味着我必须为用户的每个子类创建单独的控制器和视图。理想情况下,我会尝试用一个控制器和一组视图(即用户控制器和视图)来实现这一点。我认为这将是一个更加干燥的解决方案。为了实现这一点,我需要能够将Student类型的Desive resource对象从用户控制器传递到视图。我不确定这是否可能,但这最终是我的问题。谢谢
# GET /users/sign_up
def new
@class = params[:class]
build_resource({})
respond_with self.resource
end
#app/controllers/students_controller.rb
class StudentsController < InheritedResources::Base #-> assuming you wish to use Inherited Resources
def new
new!(@student.build_vehicle)
end
private
def permitted_params
params.permit(:student => :your, :student, :params, vehicle_attributes: [:vehicle, :attributes])
end
end
#app/views/students/new.html.erb
<%= form_for resource, as: resource_name do |f| %>
<% if resource_class == "Student" %>
...
<% end %>
<% end %>