Yoklan
Yoklan

Reputation: 211

Redirecting back from the non polymorphic side of a relationship

I have the models Event, Meeting, TaskList, and TaskItem. TaskList is in a polymorphic relationship with Event and Meeting. TaskItem is nested in TaskList, as seen in my routes below:

  concern :has_task_lists do
    resources :task_lists, only: [:new, :index, :create, :show]
  end

  resources :events, concerns: :has_task_lists do
    collection { post :import }
  end

  resources :meetings, concerns: :has_task_lists

  resources :task_lists  do
    resources :task_items, only: [:new, :index, :create] do
      member do
        patch 'complete'
      end
    end
  end

The create method can't redirect back to the view of TaskItem because of the way the controller handles polymorphic routes. With an error pointing at the load_listable method in the TaskItem controller

task_items_controller

def create
  @task_item = @task_list.task_items.new(task_item_params)
  if @task_item.save
    redirect_to @task_list, notice: "Item Created"
  end
end

task_lists_controller

def load_listable
    klass = [Event, Meeting].detect { |c| params["#{c.name.underscore}_id"]}
    @listable = klass.find(params["#{klass.name.underscore}_id"])
end

This is due to the request not having a klass as it is being sent from the non polymorphic side of the relationship. The only way I can get it to work is the do redirect_to :back, which is not desirable as it doesn't redirect to the task_item show page as it is in a partial modal.

So my question is basically how can I get it to redirect to the task_item show page which is where the create method is being called from or just not redirecting at all?

Upvotes: 0

Views: 41

Answers (1)

Yoklan
Yoklan

Reputation: 211

I've solved the issue without redoing my routes by changing the create method to the following:

def create
      @task_item = @task_list.task_items.new(task_item_params)
      if @task_item.save
      klass = "/" + @task_list.listable_type.underscore + "s"
      klass_id = "/" + @task_list.listable_id.to_s
        redirect_to klass + klass_id + task_list_path(@task_list.id), notice: "Item Created"
      else
        redirect_to klass + klass_id + task_list_path(@task_list.id), alert: "Content can't be blank."
      end
  end

Upvotes: 1

Related Questions