为什么rails不会在单表inheritance中保存类型字段

我有一个模型客户端,具有单表inheritance。 但是当我尝试提交表单时,类型字段不会保存在数据库中。 如何强制它保存类型,然后在index.html.erb上显示帐户类型。

车型/ client.rb

class Client < ActiveRecord::Base end class Suscriber < Client end class NonSuscriber < Client end 

意见/ _form.html.erb

       

clients_controller.rb

 def index @clients = Client.where(:type => params[:type]) respond_to do |format| format.html format.json {render json: @clients} end end def new @client = Client.new respond_to do |format| format.html # new.html.erb format.json { render :json => @client } end end def create @client = Client.new(params[:client]) respond_to do |format| if @client.save format.html { redirect_to @clinet, :notice => 'Client was successfully created.' } format.json { render :json => @client, :status => :created, :location => @client } else format.html { render :action => "new" } format.json { render :json => @client.errors, :status => :unprocessable_entity } end end end 

我在轨道上3.1

文档说:

“Active Record允许inheritance,方法是将类的名称存储在默认名为”type“的列中(可以通过覆盖Base.inheritance_column来更改)。

如文档中所述,您需要使用set_inheritance_column ,请查看http://apidock.com/rails/v3.1.0/ActiveRecord/Base/set_inheritance_column/class

 class Client < ActiveRecord::Base set_inheritance_column do original_inheritance_column + "_id" # replace original_inheritance_column with "type" end end 

HTH