Rails 5 before_action with method parameter - ruby-on-rails-5

Is it possible to do something like the following?
class PageController < ApplicationController
before_action :set_page, <send parameter `with_includes` to `set_page` as boolean based on conditions>
...
private
def set_page(with_includes = true)
#page = default ? Page.includes(:child) : Page
end
end

It's possible to call before_action with a lambda function:
before_action -> { set_page(your_condition_here) }
Or with a block
before_action do
set_page(your_condition_here)
end

Related

strong param method expects to `define method_name` as `controller name`

rails (5.2.2.1)
ruby 2.5.0p0
Parent controller of Country, State, City
class LocalityController < ApplicationController
def create
locality = model_name.new(locality_master_params)
respond_to do |format|
if locality.save
format.html { redirect_to locality, notice: 'Record was successfully created.' }
else
format.html { render :new }
end
end
end
private
def model_name
"#{controller_name.titleize.delete(' ').singularize}".constantize
end
def locality_params
#locality_params = %i|name code status|
end
def locality_master_params
params.require("#{controller_name.singularize}".to_sym).permit(locality_params)
end
end
State controller
class StateMastersController < LocalityController
alias_method :state_master_params, :locality_master_params
private
def locality_params
#locality_params = %i|name code status country_code|
end
end
Expectation: country-state-city controllers should be inherited from one controller and manage same templates, methods for all those controllers to DRY.
This code works fine as per the expectation.
Issue: after removing below code(as it is unnecessary):
alias_method :state_master_params, :locality_master_params
it gives error as:
ActiveModel::ForbiddenAttributesError
I've added alias_method to prevent above error.
Getting same error in other controllers too: country-city controllers.
Is there any convention to define method as state_master_params for state_master_controller?
`

Undefined method permit

I am practicing the posts in rails guide. In comments controller I write like this but it comes to error
class CommentsController < ApplicationController
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.create(params[:comment].permit(:commenter, :body))
redirect_to post_path(#post)
end
end
I'd recommend to follow up this guide
This should work:
class CommentsController < ApplicationController
def create
#article = Article.find(params[:article_id])
#comment = #article.comments.create(comment_params)
redirect_to article_path(#article)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end

How to create nice forms with active_scaffold gem on Rails 3

How to override Active Scaffold form fields for date or time?
(datepicker and calendar_date_select didn't work for me, probably
because I'm using the activescaffold gem)
How to override Active Scaffold form to select from a list of resources in the
database?
Thanks.
I was struggling this question until I figured it out. Here's an example:
class Player < ActiveRecord::Base
belongs_to :game
attr_accessible :name
end
class Game < ActiveRecord::Base
has_many :players
attr_accessible :thedate, :thetime, :winnername
end
class GamesController < ApplicationController
active_scaffold :game do |conf|
# do nothing in this example
end
end
module GamesHelper
# date select
def game_thedate_form_column (record, options)
date_select :record, :thedate, options
end
# time select
def game_thetime_form_column (record, options)
time_select :record, :thetime, options
end
# select from database resources
def game_winnername_form_column (record, options)
select_tag :winnername, options_for_select(get_players_names_arr(record)), options
end
def get_players_names_arr(game)
names = []
game.players.each do |player|
names << player.name
end
names
end
end

Ruby on Rails - Simplifying similar methods that access different variables

I'm working on a fairly simple site that allows users to choose recipe ingredients, their quantities and then shows them nutritional info based on their recipe and a large database.
Right now, I feel like I'm repeating myself a bit. I want to be able to make this "DRY" by having one method each in the Recipe and Recipe_Ingredient model that will do the same thing only accept the right parameter, which will be the type of nutrient.
Here is the relevant code in my view that currently calls two different methods (and will call more when extended to the other nutrients):
<ul>Calories <%= #recipe.total_calories %></ul>
<ul>Fat (grams) <%= #recipe.total_fat %></ul>
In my recipe model, I have methods that iterate over each of the ingredients in the recipe:
def total_calories
recipe_ingredients.to_a.sum { |i| i.total_calories }
end
def total_fat
recipe_ingredients.to_a.sum { |i| i.total_fat }
end
In the block, we call two separate methods that actually calculate the nutrients for each individual recipe ingredient:
def total_calories
ingredient.calories*ingredient.weight1*quantity/100
end
def total_fat
ingredient.fat*ingredient.weight1*quantity/100
end
This last piece is where we reference the database of ingredients. For context, here are the relationships:
class RecipeIngredient < ActiveRecord::Base
belongs_to :ingredient
belongs_to :recipe
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients
Thanks in advance for any help.
Lev
The send method with a symbol parameter works well for that kind of DRY.
<ul>Calories <%= #recipe.total :calories %></ul>
<ul>Fat (grams) <%= #recipe.total :fat %></ul>
Recipe
def total(type)
recipe_ingredients.to_a.sum { |i| i.total type }
end
RecipeIngredient
def total(type)
ingredient.send(type) * ingredient.weight1 * quantity / 100
end
You could use meta programming to dynamically add the methods. Here is a start, you can get even more DRY than this.
class DynamicTotalMatch
attr_accessor :attribute
def initialize(method_sym)
if method_sym.to_s =~ /^total_of_(.*)$/
#attribute = $1.to_sym
end
end
def match?
#attribute != nil
end
end
Recipe
class Recipe
def self.method_missing(method_sym, *arguments, &block)
match = DynamicTotalMatch.new(method_sym)
if match.match?
define_dynamic_total(method_sym, match.attribute)
send(method_sym, arguments.first)
else
super
end
end
def self.respond_to?(method_sym, include_private = false)
if DynamicTotalMatch.new(method_sym).match?
true
else
super
end
end
protected
def self.define_dynamic_total(method, attribute)
class_eval <<-RUBY
def self.#{method}(#{attribute})
recipe_ingredients.to_a.sum { |i| i.send(attribute)
end
RUBY
end
end
RecipeIngredient
class RecipeIngredient
def self.method_missing(method_sym, *arguments, &block)
match = DynamicTotalMatch.new(method_sym)
if match.match?
define_dynamic_total(method_sym, match.attribute)
send(method_sym, arguments.first)
else
super
end
end
def self.respond_to?(method_sym, include_private = false)
if DynamicTotalMatch.new(method_sym).match?
true
else
super
end
end
protected
def self.define_dynamic_total(method, attribute)
class_eval <<-RUBY
def self.#{method}(#{attribute})
ingredient.send(attribute) * ingredient.weight1 * quantity / 100
end
RUBY
end
end
Example was copied from ActiveRecord and this page: http://technicalpickles.com/posts/using-method_missing-and-respond_to-to-create-dynamic-methods/

override to_xml to limit fields returned

using ruby 1.9.2 and rails 3, i would like to limit the fields returned when a record is accessed as json or xml (the only two formats allowed).
this very useful post introduced me to respond_with and i found somewhere online that a nice way to blanket allow/deny some fields is to override as_json or to_xml for the class and set :only or :except to limit fields.
example:
class Widget < ActiveRecord::Base
def as_json(options={})
super(:except => [:created_at, :updated_at])
end
def to_xml(options={})
super(:except => [:created_at, :updated_at])
end
end
class WidgetsController < ApplicationController
respond_to :json, :xml
def index
respond_with(#widgets = Widgets.all)
end
def show
respond_with(#widget = Widget.find(params[:id]))
end
end
this is exactly what i am looking for and works for json, but for xml "index" (GET /widgets.xml) it responds with an empty Widget array. if i remove the to_xml override i get the expected results. am i doing something wrong, and/or why does the Widgets.to_xml override affect the Array.to_xml result?
i can work around this by using
respond_with(#widgets = Widgets.all, :except => [:created_at, :updated_at])
but do not feel that is a very DRY method.
In your to_xml method, do the following:
def to_xml(options={})
options.merge!(:except => [:created_at, :updated_at])
super(options)
end
That should fix you up.