samedi 20 février 2016

Rails 4+ Edit multiple objects in one form BEST PRACTICE

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?

Aucun commentaire:

Enregistrer un commentaire