我有一个模型客户端,具有单表继承。 但是当我尝试提交表单时,类型字段不会保存在数据库中。如何强制它保存类型,然后在index.html.erb上显示帐户类型。
模型/ client.rb
class Client < ActiveRecord::Base
end
class Suscriber < Client
end
class NonSuscriber < Client
end
视图/ _form.html.erb
<%= simple_form_for @client do |f| %>
<%= f.input :name %>
<%=f.input :type %>
<%= f.button :submit %>
<% end %>
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
答案 0 :(得分:2)
docs说:
“Active Record允许通过将类的名称存储在默认名为”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