STI,一个控制器 [英] STI, one controller
问题描述
我是 Rails 的新手,我有点被这个设计问题困住了,这可能很容易解决,但我无处可去:我有两种不同的广告:亮点和特价.它们都具有相同的属性:标题、描述和一张图像(带回形针).它们也可以应用相同类型的操作:索引、新建、编辑、创建、更新和销毁.
I'm new to rails and I'm kind of stuck with this design problem, that might be easy to solve, but I don't get anywhere: I have two different kinds of advertisements: highlights and bargains. Both of them have the same attributes: title, description and one image (with paperclip). They also have the same kind of actions to apply on them: index, new, edit, create, update and destroy.
我像这样设置了 STI:
I set a STI like this:
广告模型:ad.rb
class Ad < ActiveRecord::Base
end
讨价还价模式:trade.rb
Bargain Model: bargain.rb
class Bargain < Ad
end
高亮模型:highlight.rb
Highlight Model: highlight.rb
class Highlight < Ad
end
问题是我只想有一个控制器 (AdsController
) 来执行我根据 URL 在特价或亮点上所说的操作,比如 www.foo.com/bargains[/...] 或 www.foo.com/highlights[/...].
The problem is that I'd like to have only one controller (AdsController
) that executes the actions I said on bargains or highlights depending on the URL, say www.foo.com/bargains[/...] or www.foo.com/highlights[/...].
例如:
- 获取 www.foo.com/highlights => 所有重点广告的列表.
- GET www.foo.com/highlights/new => 表单以创建新的亮点等等...
我该怎么做?
谢谢!
推荐答案
首先.添加一些新路线:
First. Add some new routes:
resources :highlights, :controller => "ads", :type => "Highlight"
resources :bargains, :controller => "ads", :type => "Bargain"
并修复AdsController
中的一些操作.例如:
And fix some actions in AdsController
. For example:
def new
@ad = Ad.new()
@ad.type = params[:type]
end
有关所有控制器工作的最佳方法,请查看此评论
仅此而已.现在你可以去 localhost:3000/highlights/new
并且新的 Highlight
将被初始化.
That's all. Now you can go to localhost:3000/highlights/new
and new Highlight
will be initialized.
索引操作可以如下所示:
Index action can look like this:
def index
@ads = Ad.where(:type => params[:type])
end
转到localhost:3000/highlights
,将出现亮点列表.
讨价还价的相同方式:localhost:3000/bargains
Go to localhost:3000/highlights
and list of highlights will appear.
Same way for bargains: 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 %>
这篇关于STI,一个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!