0

I'm trying to create a nested path for a show action of a nested resource

user.rb

has_many :fan_receives, as: :fanzone_owner, class_name: "FanActivity"

fan_activity.rb

belongs_to :fanzone_owner, polymorphic: true

In my routes.rb

match ":fanzone_owner_id/posts/:id", to: "fan_activities#show", via: :get

The path works, but the fanzone_owner_id could be anything. For an example,

example.com/1/fan_activities/2 works
example.com/2/fan_activities/2 also works
example.com/anythingatall/fan_activities/2 also works

I would like to make it so the fanzone_owner_id of the url must match the foreign key of the fan_activity, otherwise we redirect to 404.

Would I do this with validation check of the url in the controller? I'm not sure if this approach is correct

oniiko
  • 41
  • 6

2 Answers2

0

Based on the informations I would suggested to use nested routes.

resources :fanzone_owner do
 resources :fan_receive
end

For that you should've also nested attributes ready, otherwise the above routing would make no sense at all. This tutorial could be helpful.

CottonEyeJoe
  • 720
  • 1
  • 7
  • 28
  • In my case, things get a little complicated because fanzone_owner is set as polymorphic and fan_receives are actually another class called 'fan_activities' I tried using the nested routes, but it resulted in the same problem in the question. My goal is to just have the ':show' route for fan_receives display the context of who the fanzone_owner is. – oniiko Feb 01 '17 at 23:12
0

I figured out what was wrong. I just had to use the params from the url in the controller for the show action.

In the fan_activities_controller.rb

@user = User.find(params[:fanzone_owner_id])
@fan_activity = @user.fan_receives.find(params[:id])

If the user is not found or the user isn't the fanzone_owner, then it would be a 404.

oniiko
  • 41
  • 6