使用自定义类和simple_form创建记录

时间:2012-04-06 13:38:46

标签: ruby-on-rails ruby

我有这个型号:

class User < ActiveRecord::Base
  # abstract
end

class Company < User

end

class Person < User

end

如何创建具有类型选择的表单?

<%= simple_form_for(@user) do |f| %>
    <%# I would like to have a selector of classes ["Company","Person"] %>
    <%= f.input :type %>
    <%= f.input :name %>
<% end %>

在控制者中,我应该编写什么代码?

@user = User.new(params[:user]) # Pb params[:user][:type] have no effect

2 个答案:

答案 0 :(得分:0)

您无法批量指定type属性。你可以这样做:

type = params[:user].delete :type
@user = User.new(params[:user])
@user.type = type
@user.save

答案 1 :(得分:0)

这就像你能做到的那样简洁:

@@classmap = { :person => Person, :company => Company }
@@Classmap[params[:user].delete :type].new(params[:user])

请勿将params[:type]直接转换为班级名称。这是一个等待被利用的安全漏洞。

相关问题