Sasha
Sasha

Reputation: 6466

Rails Routes with multiple model ids

I've got an app with an Item model and a Fixer model. Each Item belongs to a Fixer, and Fixers can have many items. I want to create a "log" page where a particular fixer can update information on a particular Item associated with them. Ideally something like this

www.myappname.com/fixers/<fixer_id>/log/<item_id>

I'm fairly new to Rails, so I'm not really sure how to figure out the routing/controller for this one. I looked in the Rails Guide section on routing, and the only thing that looked similar to what I want is Nested Models, but I ideally don't want to nest the models, because while items may technically "belong_to" fixers, that's not really the case in the real world (fixers are just associated, and belong_to was the most sensible way), and there's no other part of the relationship that requires/makes sense with nesting. More importantly, I don't really get what nesting the models means or does, and I try to avoid implementing solutions that I don't fully understand.

If nesting's the way to go, let me know, but otherwise, how might I go about routing this? I've tried this in my routes.rb file:

match 'fixers/:id/log/:id' => 'fixers#log'

and created log.html.erb, but I don't know how I'd select the params of that in a controller (how does it know which ":id" I'm selecting for? Is there a better way to do this?

Thanks!

Upvotes: 1

Views: 2934

Answers (2)

mechanicalfish
mechanicalfish

Reputation: 12826

Nested resources are used for one to many relationships as you can read in Rails routing guide.

You can name the params any way you see fit, it doesn't have to be :id. For example:

match 'fixers/:id/log/:item_id' => 'fixers#log'

and in your controller:

@fixer = Fixer.find(params[:id])
@item = Item.find(params[:item_id])

Upvotes: 1

felipeclopes
felipeclopes

Reputation: 4070

Since they are associated with each other you may try to use the nested routing:

resources :fixers do
  resources :log
end

Upvotes: 3

Related Questions