我是 Rails 的新手,我有点被这个设计问题困住了,这可能很容易解决,但我没有得到任何结果: 我有两种不同的广告:亮点和特价。它们都具有相同的属性:标题、描述和一张图片(带有回形针)。它们也有相同类型的操作可应用于它们:索引、新建、编辑、创建、更新和销毁。
我这样设置 STI:
广告模型:ad.rb
class Ad < ActiveRecord::Base
end
讨价还价模型:bargain.rb
class Bargain < Ad
end
高亮模型:highlight.rb
class Highlight < Ad
end
问题是我只希望有一个 Controller (AdsController
) 来执行我所说的根据 URL(比如 www.foo.com/bargains[/...] 或 www.foo.com/highlights[/...]。
例如:
- 获取 www.foo.com/highlights => 所有突出显示的广告的列表。
- GET www.foo.com/highlights/new => 形成一个新的亮点 等等……
我该怎么做?
谢谢!
最佳答案
首先。添加一些新路线:
resources :highlights, :controller => "ads", :type => "Highlight"
resources :bargains, :controller => "ads", :type => "Bargain"
并修复 AdsController
中的一些操作。例如:
def new
@ad = Ad.new()
@ad.type = params[:type]
end
有关所有此 Controller 工作的最佳方法,请查看 this comment
就是这样。现在您可以转到 localhost:3000/highlights/new
,新的 Highlight
将被初始化。
索引操作可以如下所示:
def index
@ads = Ad.where(:type => params[:type])
end
转到 localhost:3000/highlights
将显示突出显示列表。
讨价还价的方式相同:localhost:3000/bargains
等等
网址
<%= link_to 'index', :highlights %>
<%= link_to 'new', [:new, :highlight] %>
<%= link_to 'edit', [:edit, @ad] %>
<%= link_to 'destroy', @ad, :method => :delete %>
因为是多态的:)
<%= link_to 'index', @ad.class %>
关于ruby-on-rails - STI,一个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5246767/