【问题标题】:STI and ControllerSTI 和控制器
【发布时间】:2011-07-30 06:55:40
【问题描述】:

在我的模型中,我像这样使用 STI

车辆型号:vehicle.rb

class Vehicle < ActiveRecord::Base
end

车型:car.rb

class Car < Ad
end

总线型号:bus.rb

class Bus < Ad
end

仅使用一个控制器最有效的方法是什么?

谢谢

【问题讨论】:

  • 您能否详细说明您要在控制器中执行的操作?
  • 我认为是的。有人也可以提供模型表的示例吗?另一个问题是我现有的链接可以工作吗?例如vehicles_path ?

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

在我看来,最好的方法是这样做:(我不确定这是否是最好和更有效的方法)

首先。添加一些新路线:

resources :cars, :controller => "vehicle", :type => "Car"
resources :buses, :controller => "vehicle", :type => "Bus"

为你的控制器添加一个私有方法,将你的类型参数转换为你想要使用的实际类常量:

def vehicle_type
  params[:type].constantize
end

然后在控制器中你可以做的动作:

def new
  vehicle_type.new
end

def create
  vehicle_type.new(params)
  # ...
end

def index
  vehicle_type.all
end

网址

<%= link_to 'index', :cars %>
<%= link_to 'new', [:new, :car] %>
<%= link_to 'edit', [:edit, @vehicle] %>
<%= link_to 'destroy', @vehicle, :method => :delete %>

因为是多态的:)

<%= link_to 'index', @vehicle.class %>

PS:我的回答来自 stackoverflow.com/questions/5246767/sti-one-controller 和我的经验

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    相关资源
    最近更新 更多