Rails - 有两个父母的嵌套资源
假设我有一个带有两个父模型的子模型:
Event has_many tickets
Person has_many tickets
Ticket belongs_to Event
Ticket belongs_to Person
路由已映射,因此票证始终嵌套在事件或人员中:
resource :people do
resources :tickets
end
resources :events do
resources :tickets
end
如何按父资源确定我的 Ticket_Controller CRUD 操作的范围?
现在我正在测试参数并使用条件语句:
class TicketController
before_filter :get_person
before_filter :get_event
def index
if @person do
...
elsif @event do
...
end
respond_to
...
end
end
对于每个操作来说这似乎有点乏味。有没有更 Rails-y DRY 的方法来做到这一点?
Say I have a child model with two parent models:
Event has_many tickets
Person has_many tickets
Ticket belongs_to Event
Ticket belongs_to Person
Routes are mapped so Ticket always nests within Event or Person:
resource :people do
resources :tickets
end
resources :events do
resources :tickets
end
How do I scope my ticket_Controller CRUD actions by the parent resource?
Right now I'm testing for params and using conditional statements:
class TicketController
before_filter :get_person
before_filter :get_event
def index
if @person do
...
elsif @event do
...
end
respond_to
...
end
end
That seems a bit tedious to do for every action. Is there a more rails-y DRY way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:
有很多方法可以改进上面的代码。
您还可以按如下方式编写路线:
You could do this:
There are many ways of improving the code above.
You could also write the routes as follows:
最干燥的方法是使用继承资源:
Boom...done。但是,如果您出于某种原因无法使用inherited_resources,则可以为
get_parent
设置一个过滤器,而不是使用get_person
或get_event
,如下所示:编辑:我在上面添加了 @template_prefix 来解决您在评论中提到的模板问题。
The most DRY would be to use inherited_resources:
Boom...done. If you can't use inherited_resources for whatever reason, though, rather than
get_person
orget_event
you could set up a filter toget_parent
like so:Edit: I added the @template_prefix above to address the template issue you mentioned in your comment.