【问题标题】:Why rails doesn't save type field in single table inheritance为什么rails不在单表继承中保存类型字段
【发布时间】:2017-03-09 21:57:11
【问题描述】:

我有一个模型客户端,具有单表继承。 但是当我尝试提交表单时,类型字段不会保存在数据库中。如何强制它保存类型,然后在 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      

我在 Rails 3.1 上

【问题讨论】:

  • 你的控制器在做什么?
  • 我已经添加了控制器索引,创建和新建

标签: ruby-on-rails inheritance


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-06-30
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多