Accessing controller params inside of rails model method - ruby-on-rails

I have params[:tab] within my activities controller. This is used to switch between different tabs on a view. I want to be able to access this param within my model method self.search_my_work.
Activities controller
if params[:tab].blank? || params[:tab] == 'active' || params[:tab] == 'inactive' || params[:tab] == 'overdue'
Activities model
if tab == 'overdue'
do this
else
do this
end
As it stands right now I get a Name error.
I am aware it needs instantiated but I don't know how.

You can't directly access controller params in your model and should not.
Solution:
Pass it as a param to the method
E.g:
# controllers/activities_controller.rb
Activity.results_for(params[:tab])
And use it
# models/acctivity.rb
def self.results_for(status)
where(status: status)
end

Related

i have to create one session in user model,showing flags(true or false),how can i access those method in views

This is user model
def is_federated
session[:federatedIdHeader] == true
end
i have added this session in initializers
session[:federatedIdHeader] == true
How to access that session[:federatedidHeader] in views

ruby2/rails4: How do I set a variable in a model that can then be available to multiple methods

I have a model for Event. This is a super simple model that has two before_save callbacks.
One of them is:
def set_note
if status == "ON"
core = RubySpark::Tinker.new(ENV["COREID"])
core.digital_write(0, "HIGH")
elsif status == "OFF"
core = RubySpark::Tinker.new(ENV["COREID"])
core.digital_write(0, "LOW")
end
end
I previously had the 'core = RubySpark' outside of the method but the app returned an error that 'core' was an invalid local variable. Can I set it as a instance Variable? IS it ok to set an instance variable in a model?
My personal preference for this would be to extract some of the code into another method.
Something like this:
def set_note
if status == "ON"
core_digital(0, "HIGH")
elsif status == "OFF"
core_digital(0, "LOW")
end
end
def core_digital(num, val)
core_method.digital_write(num, val)
end
def core_method
RubySpark::Tinker.new(ENV["COREID"])
end
You would probably want to name the method something more meaningful than my example.
It really depends on how many times this method gets called, or really, how many times RubySpark::Tinker.new(ENV["COREID"] gets called. If it's only one time then declaring it as an instance variable is not necessary. You could do:
def set_note
core = RubySpark::Tinker.new(ENV["COREID"])
if status == "ON"
core.digital_write(0, "HIGH")
elsif status == "OFF"
core.digital_write(0, "LOW")
end
end
If however, you think that this method gets executed multiple times in the same request then you could make use of memoization changing core to an instance variable and using the ||= operator.
def set_note
#core ||= RubySpark::Tinker.new(ENV["COREID"])
if status == "ON"
#core.digital_write(0, "HIGH")
elsif status == "OFF"
#core.digital_write(0, "LOW")
end
end
Yes. Using instance variables is the designed way for an object to keep information that should be available for multiple methods to be able to access.
Only that instance of the object will have that value (as implied by the name instance variable) so it won't negatively affect other instances.
As has already been suggested there are ways that you could use less repetition by abstracting part of your method into another method. This is a good idea, but the basic answer to your question is just "Yes, that's what it's for."

access controller's object attributes in view page in ROR

I am new to ROR and learning it. In my controller I have an admins
record and I am passing that admin object to the admin's view page to
get the name of the admin. But when I try to access the name it
showing a error:
undefined method 'name' for :current_admin:Symbol
Please help..
Please find my code below
Sessions Controller
def create
admin=Admin.find_by_email(params[:session][:email].downcase)
if admin && admin.authenticate(params[:session][:password])
redirect_to(admins_index_path(:current_admin=>admin))
end
end
In view page of index_admin
In your action for index_admin you need to get an admin object from your param. The value of a param is usually just a string.
def create
admin=Admin.find_by_email(params[:session][:email].downcase)
if admin && admin.authenticate(params[:session][:password])
redirect_to(admins_index_path(:current_admin => admin.id)) # pass the id, not the object
end
end
def index_admin
#current_admin = Admin.find(params[:current_admin])
end
In you index_admin.html.erb:
Hi <%= #current_admin.name %>

How do I add to a rails session when submitting to same page?

I have a need for a number of form pages in a row where each form submits to the same index page. On each submit a different view is displayed depending on how the input fields are validated.
Controller:
class FormsController < ApplicationController
include FormsHelper
def index
#if we know what view to show, show it, else show first view in the flow
if(!session.has_key?(:flow_page))
set_flow_page
end
# if form was submitted, I want to add this pages submit data to what I already have in session[:quote]
if(params.has_key?(:form))
temp = params[:form]
form = session[:quote]
form.merge(temp)
#session[:quote].deep_merge!(session[:temp])
end
# other stuff
if params[:back] == "Back" && params[:flow][:previous_page] != "refused"
session[:flow_page] = params[:flow][:previous_page]
end
if params[:next] == "Next"
session[:flow_page] = params[:flow][:next_page]
end
end
end
Could someone tell me how to add the form data from each view into the session[:quote] without overwriting the whole block each time?
Not sure what you are trying to do but lets assume you want to keep history of your forms which hit same method on submit. For bellow code to work you need to add hidden form field with UID for each form. Name that field "form_name"
# init form cache, if not initiated before
session[:quote] = {} unless session.has_key(:quote)
# keys to be excluded
filter_out = [:form_name,:controller, :action]
# store to cache, with form UID / we filter out params we don't need
session[params[:form_name]] = params.dup.keep_if { |k,v| !filter_out.include?(k) }

Ruby on Rails: how do I call an action that has params from another action

So I want to do this:
save_to_library(params) if params[:commit] == "lib"
but save_to_library apparently doesn't take any arguments.
how do actions get params if they don't take arguments?
(I know this action works when I link to it directly... just trying to streamline usability)
Your controller processes the params and makes them available to you through an accesor method, they are available to your whole controller without the need to pass it around in method parameters.
params is a global hash, imagine it as if it were defined outside the method:
params = {:commit => "lib"}
def save_to_library
#var = params[:commit]
# etc..
end
If you want to do some conditional actions you can just do this:
def update
save_to_library if params[:commit] == "lib"
end
def save_to_library
#var = params[:commit] # #var = "lib"
# etc..
end
And it should just work.

Resources