2011-11-29 35 views
2

我有一個模型客戶端,單表繼承。 但是當我嘗試提交表單時,類型字段不會保存在數據庫中。我如何強制它保存該類型,然後在index.html.erb上顯示帳戶類型。爲什麼rails不能保存單表繼承中的類型字段

型號/ 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

什麼是你的控制器在做什麼? – jdl

+0

我已經添加了控制器索引,創建和新建 – blawzoo

回答

2

docs說:

「活動記錄允許繼承由一列在默認情況下被命名爲存儲類的名稱‘類型’(可以通過覆蓋基本改變。 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