具有两个父级的嵌套资源

具有两个父级的嵌套资源

本文介绍了Rails - 具有两个父级的嵌套资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有两个父模型的子模型:

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

路由被映射,所以Ticket 总是嵌套在Event 或Person 中:

Routes are mapped so Ticket always nests within Event or Person:

resource :people do
  resources :tickets
end

resources :events do
  resources :tickets
end

如何通过父资源确定我的 ticket_Controller CRUD 操作的范围?

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

对每个动作都这样做似乎有点乏味.有没有更符合 rails-y DRY 的方法来做到这一点?

That seems a bit tedious to do for every action. Is there a more rails-y DRY way to do it?

推荐答案

最枯燥的方法是使用inherited_resources:

The most DRY would be to use inherited_resources:

class TicketsController < InheritedResources::Base
  belongs_to :event, :person, :polymorphic => true
end

砰……完成了.但是,如果您由于某种原因不能使用inherited_resources,而不是get_personget_event,您可以像这样为get_parent 设置过滤器:

Boom...done. If you can't use inherited_resources for whatever reason, though, rather than get_person or get_event you could set up a filter to get_parent like so:

class TicketsController < ActionController::Base
  before_filter :get_parent

  def get_parent
    if params[:person_id]
      @parent = Person.find(params[:person_id])
      @template_prefix = 'people/tickets/'
    elsif params[:event_id]
      @parent = Event.find(params[:event_id])
      @template_prefix = 'events/tickets/'
    else
      # handle this case however is appropriate to your application...
    end
  end

  # Then you can set up your index to be more generic
  def index
    @tickets = @parent.tickets
    render :template => @template_prefix + 'index'
  end
end

我在上面添加了@template_prefix 以解决您在评论中提到的模板问题.

I added the @template_prefix above to address the template issue you mentioned in your comment.

这篇关于Rails - 具有两个父级的嵌套资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 14:33