简体   繁体   中英

Handling Rails routes/models with belongs_to relationship

So this may be more of a convention question, but im writing a todo app to learn how to use rails as an API (Im somewhat intermediate with using rails normally) but this time im using it with React for the front end.

Im making a simple todo app, two models in particular being "Lists" and "ListItems". Lists has_many ListItems of course, and a ListItem belongs_to a List.

So naturally I have the routes set up like so:

      resources :lists do
        resources :list_items
      end

Giving me routes similar to: /api/v1/lists/:list_id/list_items etc.., However I saw some people doing a similar app set it up like:

    namespace :v1 do
      resources :list_items
      resources :lists
    end

Which confuses me because how would you handle passing the actual "List" params to the route, when the route itself would not have a List_id param?

Or would this more be used for a join table somehow..but you would still have to populate the List_id regardless when creating a list_item for a specific list correct?

Is there a preferred way of doing this as far as routing goes? (And I suppose creating tables?) Since a has_many_through seems not really necessary in this case?

Unless there is more to the story, you are doing it the more conventional way. I suggest your can safely disregard that not-nested approach. The only enhancement I suggest is using shallow: true , like:

namespace :api do 
  namespace :v1 do 
    resources :lists do 
      resources :list_items, shallow: true
    end
  end
end

You can read more about shallow nesting in the guide .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM