Use params value with variable in ruby on rails? [duplicate] - ruby-on-rails

This question already has an answer here:
Use variable in parameter ruby on rails? [closed]
(1 answer)
Closed 7 years ago.
I want to check if param key exists with a variable name and if it exists I want to use value something like params[filenamestring[-1]].
filenamestring is any array generate with split

If you variable is a hash than here is your answer
if params.has_key?(filenamestring[-1])
param_value = param[filenamestring[-1]]
end

You can check existence of key using has_key? method:
key = filenamestring[-1]
# or, key = filenamestring.last
if params.has_key?(key)
value = params[key]
# do stuff with value
end

Related

Delete a hash from array of hashes in rails [duplicate]

This question already has answers here:
Deleting a hash from array of hashes in Ruby
(2 answers)
Closed 5 years ago.
I have array of hashes in json format, and I have to remove one of the hash from that array, I am iterating that array and if that particular key/ value matches i am deleting that hash,
I found clear() method but, clear leaves the {}, which I don't require
I want the whole hash to be removed
[{"question":"0a2a3452","answer":"lopq"},
{"question":"58deacf9","answer":"admirationo"},
{"question":"32c53e","answer":"acion"},
{"question":"b5546bcf","answer":"figure"},
{"question":"4f246a10","answer":"zelta"},
{"question":"bf546c04","answer":"deltaa"}]
i.e if my key matches as "0a2a3452", I want to delete the first hash
You can do with delete_if method:
arr = [{"question":"0a2a3452","answer":"lopq"},
{"question":"58deacf9","answer":"admirationo"},
{"question":"32c53e","answer":"acion"},
{"question":"b5546bcf","answer":"figure"},
{"question":"4f246a10","answer":"zelta"},
{"question":"bf546c04","answer":"deltaa"}]
arr.delete_if {|a| a[:question] == '0a2a3452' }
Try this:
items = [
{"question":"0a2a3452","answer":"lopq"},
{"question":"58deacf9","answer":"admirationo"},
{"question":"32c53e","answer":"acion"},
{"question":"b5546bcf","answer":"figure"},
{"question":"4f246a10","answer":"zelta"},
{"question":"bf546c04","answer":"deltaa"}
]
items = items.reject {|i| i[:question] == '0a2a3452'}

String to method name [duplicate]

This question already has answers here:
How to call methods dynamically based on their name? [duplicate]
(5 answers)
Closed 5 years ago.
I cant seem to follow this answer but maybe it's different from what I'm trying to achieve.
I have a string, that string can be different at time, I need to convert that string into a defined method name:
action = "get_name"
# The method
def get_name
puts "James"
end
# Calling the method
action # => undefined method `action' for main:Object
action can be any of my defined methods and the names are in a string format. Could I say action.to_method, you get what I mean ;)
I dont think I could say action.to_sym?
method(action).call
or
public_send(action)
Example:
method(action).call
#=> James
public_send(action)
#=> James
Be aware, though, that none of the above cares about the context, where was method originally defined, so both will call it in the context of the current object.

Rails: set params but do not save [duplicate]

This question already has answers here:
Rails update_attributes without save?
(4 answers)
Closed 6 years ago.
What's the call to update a Rails record with new params, say, stored in a hash variable? This:
#user.update(hash)
Will save the record, and since I want to put the call in a callback I don't want to save it, just prepare it to be saved correctly in the callback.
You can use attributes= to set the attributes but not save the record.
#user.attributes = hash
New attributes will be persisted in the database when the object is saved. See http://apidock.com/rails/ActiveRecord/AttributeAssignment/attributes
You can do:
#user.attributes = hash
or
#user.assign_attributes hash
Keep in mind that neither of these will return the object you're working on. If you want that, try Object#tap:
#user.tap { |u| u.assign_attributes hash }

In Rails, How can I convert params[:id] to Integer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Guys I am trying to retrieve specific records from the DB using params[:id].
x = Authors.find(params[:id])
We cannot use FIND with string like this because the parameter is always passed by HTTP as a string:
I also tried this code but I do not know why it always returns 0 while the passed parameter is 4
x = Authors.find(params[:id]).to_i
So how can I do something like casting for ID Parameter or Any method to convert HTTP passed strings to integers
You don't really have to convert strings to integer to use find. It should be able to convert the string for you.
Just to give an example:
Author.find(2) # => #<Author:1234>
Author.find("2") # => #<Author:1234>
Author.find("2") == Author.find(2) # => true
Try using pry to see if what you are passing is correct. Hope this helps clear out the method.
I think you might have just misplaced your type casting:
x = Authors.find(params[:id].to_i)
you can use this:
x = Authors.find(params[:id].to_i)
However,
x = Authors.find(params[:id])
is also correct as it returns the correct author.
Before using the above one you can check whether the params[:id] is present or not:
if params[:id].present?
x = Authors.find(params[:id])
end
After I used the method .inpect on the parameter which I am trying to grab, I found that it was nil. I was grabbing it wrongly. By the way, I was trying to grab another parameter not :id but :artCatName and Here are my passed parameters:
{"utf8"=>"✓", "authenticity_token"=>"tQetEjfE+stm/yXfQWyS9pEhznu+zeNwrHPa6BNjWsfd4bcv/PFsYRcMT‌​1L8y2obJt6xNTcoOFNgzq6R6OcjMw==", "category"=>{"artCatName"=>"1"}, "article"=>{"artTitle"=>"bb", "artBody"=>"b"}, "commit"=>"Publish", "controller"=>"articles", "action"=>"create"}
Here how I grabbed :artCatName and how I converted to integer
params[:category][:artCatName].to_i

meaning of * in ruby function [duplicate]

This question already has answers here:
What does the (unary) * operator do in this Ruby code?
(3 answers)
Closed 7 years ago.
I have a basic question about the mearning of * in a function call which I haven't been able to understand from online docs:
def self.new(*args, &block)
What does *args mean in the function call above?
consider a following method
def user(user_name)
puts user_name
end
so when you call
user("RPV")
Output:
RPV
=> nil
but what if you pass more then one argument like
user("RPV", "Marek")
it will give an error
wrong number of arguments (2 for 1)
To avoid this kind of error splat(*) operator is helpful
def user(*user_name)
puts user_name
end
and when you pass more than one argument it handles converts it in array
user("RPV", "Marek")
output:
RPV
Marek
nil
it makes user_name as an array
def user(user_name)
p user_name
end
user("RPV", "Marek")
output:
["RPV", "Marek"]
Hope you got the use of it.
It means you can pass any number of arguments that will be stored in args table inside of this method. Take a look: https://endofline.wordpress.com/2011/01/21/the-strange-ruby-splat/

Resources