1

I have a User, Drinks, Gyms, Foods Model.

class User < ActiveRecord::Base
 has_many :drinks
 has_many :foods
 has_many :gyms
end

I track the number of drinks a user had during the day and save it in the database.I do the same with Foods and Gyms.

I have a User and a Session (for login) controller. So far I haven't needed a controller for my "passiv" Models (Drink, Food, Gym).

Now I have one page with a form on which the User can change the entries of all tables(Drink, Food, Gym) of the previous day.

I think I need to use fields_for in the form to edit objects of multiple Models in one form.

However I don't know how many controllers I need and where I should put in all the business logic... I don't want to do anything quick and dirty, but rather follow certain Best Practices.

My approach so far:

  • A lot of forms on one page

    <%= form_for :running, url: data_update_user_path do |f| %>
    <%= form_for :drinks, url: data_update_user_path do |f| %>
    <%= form_for :food, url: data_update_user_path do |f|
    
  • One DataController who handles all the different updates (It's basically a big if elsif)

    class DataController 
     def update
    
      if params[:drinks]
       #update drinks
      elsif params[:foods]
       #update foods
      elsif params[:gyms]
       #update gyms
      end
     end
    end
    


So my question: What is the best practice in such a situation?

1 Answer 1

2

Use nested form with only one controller; the users controller, the update action for the user will update it's related models as well when you use accepts_nested_attributes_for so basically your user model will be

class User < ActiveRecord::Base
  has_many :foods
  has_many :drinks
  has_many :gyms
  accepts_nested_attributes_for :foods, :drinks, :gyms
end

And the for for user will contain fields_for foods, drinks and gyms

Don't forget in your users controller if you are using strong_parameters to permit the attributes of the nested models

def user_params
 params.require(:user).permit(:id, .... , foods_attributes: [:id, :destroy, ....], gyms_attributes: [:id, :_destroy, ....], drinks_attributes: [:id, :_destroy, ....])
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.