Issues Creating Custom Rails Method -


i have app following structure:

  • a mealplan includes 1 recipe each day of week.
  • a recipe has_many ingredients.
  • a grocery 1 item on user's grocery list.

i want create custom method when button clicked, runs grocery.create on each ingredient recipes on mealplan.

i have following mealplans#index method, can see how they're defined. (all of happening on index view:

  def index     @mealplans = mealplan.where(user_id: current_user.id)     @mealplan = mealplan.new     @recent = mealplan.where(user_id: current_user.id).where("created_at > ?", time.now.beginning_of_week).order("week_starting").last     @recipes = recipe.where(user_id: current_user.id)     @monday = recipe.where(id: @recent.monday)[0] if @recent.present?     @tuesday = recipe.where(id: @recent.tuesday)[0] if @recent.present?     @wednesday = recipe.where(id: @recent.wednesday)[0] if @recent.present?     @thursday = recipe.where(id: @recent.thursday)[0] if @recent.present?     @friday = recipe.where(id: @recent.friday)[0] if @recent.present?     @saturday = recipe.where(id: @recent.saturday)[0] if @recent.present?     @sunday = recipe.where(id: @recent.sunday)[0] if @recent.present?   end 

i have dummy mealplans#add_to_list method set in controller, feel doing way violates "skinny controllers, fat models" principle of rails.

can clue me in "railsiest" way accomplish task, according best practices?

check gem "nested_form" gem creating multiple records.

for better implementation create scope under mealplan model.

class mealplan < activerecord::base    scope :recent, ->(uid) { where(user_id: uid).where("created_at > ?", time.now.beginning_of_week).order("week_starting").last}     # find day name of recent mealplan    def recent_day_name      created_at.strftime("%a")    end end 

in controller can use scope this:

def index   @mealplan = mealplan.new   @recent = mealplan.recent(current_user.id)   if @recent     recent_day = @recent.recent_day_name     @day = recipe.find(id: @recent.send(recent_day))   end end 

there no needs create @mealplans , @recipes instance variable on controller site:

@mealplans = mealplan.where(user_id: current_user.id) @recipes = recipe.where(user_id: current_user.id) 

you can mealplans , recipes details current_user object.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -