stewart715
stewart715

Reputation: 5647

Do I need a controller for this situation?

As we all do, I have a Users controller/model.

I want to add a 'favorite_car' model to pull their favorite cars from the favorite_cars table in the database. In models/users.rb I have has_many favorite_cars and in models/favorite_car.rb I have belongs_to user

Can I use and store data this way without a favorite_cars controller?

Upvotes: 0

Views: 84

Answers (2)

Tom
Tom

Reputation: 408

If you want to update 'Favorite Car' from the user create form, look at accepts_nested_attributes. (http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)

Your user model would then "accepts_nested_attributes_for :favorite_car". In your view you can combine the user form fields and the car form fields and post back to the user controller.

If you want to access the favorite_car model outside of its association with a user, it would definitely need its own controller.

Upvotes: 1

tadman
tadman

Reputation: 211560

It is typical to have a controller associated with each type of model you are able to create, read, update or destroy as this maps quite neatly to the REST methodology.

If you have a FavoriteCar model, you should probably have a FavoriteCarsController associated with it to help create these. If the model itself is actually a join between User and Car, you may add this as a method to the CarsController as an action favorite which does the same thing.

Upvotes: 0

Related Questions