为什么Rails不能在单表继承中保存类型字段 [英] Why rails doesn't save type field in single table inheritance

查看:100
本文介绍了为什么Rails不能在单表继承中保存类型字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a model client, with single table inheritance. But the when I try to submit the form, the type field doesn't get saved in the database. How can I force it to save the type and then display the account type on index.html.erb.

models/client.rb

class Client < ActiveRecord::Base

end

class Suscriber < Client

end

class NonSuscriber < Client

end 

views/_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上

推荐答案

文档说:

"Active Record通过将类的名称存储在默认情况下称为类型"的列中(可以通过覆盖Base.inheritance_column进行更改)来允许继承."

"Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed by overwriting Base.inheritance_column)."

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

As mentioned in the doc, you need to use set_inheritance_column, have a look at 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

这篇关于为什么Rails不能在单表继承中保存类型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆