Rails testing for params key - ruby-on-rails

I'm trying to sort out a problem where I need to write the following and test to see if a params key is being passed:
if params.has_key? :transfer_date(1i)
params[:call].parse_time_select! :transfer_date
end
I can test against a params key like :transfer but the params being passed by my time parsing gem passes transfer_date(1i), transfer_date(2i), etc.
How do I write the above statement with the right syntax so I can test for the transfer_date(1i) params key?

You can quote the symbol's content:
if params.has_key? :'transfer_date(1i)'
or, if params is guaranteed to be the usual ActiveSupport::HashWithIndifferentAccess, you could just check for a string key:
if params.has_key? 'transfer_date(1i)'

Related

rails unable to access a value in the params hash

I have a params hash that looks like this:
puts contact_params
=> {"classifiable_classification_codes_attributes"=>{"0"=>{"id"=>"5", "relateds_attributes"=>{"0"=>{"classifiable_id"=>"6", "id"=>"15"}}}}}
So I expect when I do this contact_params["classifiable_classification_codes_attributes"], I subsequently get {"0"=>{"id"=>"5"...
In fact, that is exactly what happens in the console:
> contact_params["classifiable_classification_codes_attributes"]
=> {"0"=>{"id"=>"5", "relateds_attributes"=>{"0"=>{"classifiable_id"=>"6", "id"=>"15"}}}}
However, in the controller when I try do this, it returns a nil value, as if classifiable_classification_codes_attributes is not a key. I also tried the symbol form :classifiable_classification_codes_attributes. But neither of them return any results.
What might I be doing wrong?
I'm guessing this might be a Strong Parameters issue in which case you need to add something like
private
def my_params
params.require(:classifiable_classification_codes_attributes).permit(: id, :relateds_attributes)
end
Read more at: http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

Rails access hash value

I'm playing around with Netflix's Workflowable gem. Right now I'm working on making a custom action where the user can choose choices.
I end up pulling {"id":1,"value":"High"} out with #options[:priority][:value]
What I want to do is get the id value of 1. Any idea how to pull that out? I tried #options[:priority][:value][:id] but that seems to through an error.
Here's what the action looks like/how I'm logging the value:
class Workflowable::Actions::UpdateStatusAction < Workflowable::Actions::Action
include ERB::Util
include Rails.application.routes.url_helpers
NAME="Update Status Action"
OPTIONS = {
:priority => {
:description=>"Enter priority to set result to",
:required=>true,
:type=>:choice,
:choices=>[{id: 1, value: "High"} ]
}
}
def run
Rails.logger.debug #options[:priority][:value]
end
end
Here's the error:
Error (3a7b2168-6f24-4837-9221-376b98e6e887): TypeError in ResultsController#flag
no implicit conversion of Symbol into Integer
Here's what #options[:priority] looks like:
{"description"=>"Enter priority to set result to", "required"=>true, "type"=>:choice, "choices"=>[{"id"=>1, "value"=>"High"}], "value"=>"{\"id\":1,\"value\":\"High\"}", "user_specified"=>true}
#options[:priority]["value"] looks to be a strong containing json, not a hash. This is why you get an error when using [:id] (this method doesn't accept symbols) and why ["id"] returns the string "id".
You'll need to parse it first, for example with JSON.parse, at which point you'll have a hash which you should be able to access as normal. By default the keys will be strings so you'll need
JSON.parse(value)["id"]
I'm assuming the error is something like TypeError: no implicit conversion of Symbol into Integer
It looks like #options[:priority] is a hash with keys :id and :value. So you would want to use #options[:priority][:id] (lose the :value that returns the string).

Dynamically creating hash key name in Rails 4

Is it possible to dynamically create key names of a hash? I'm passing the following hash parameters:
params[:store][:store_mon_open(5i)]
params[:store][:store_mon_closed(5i)]
params[:store][:store_tue_open(5i)]
params[:store][:store_tue_closed(5i)]
.
.
.
params[:store][:store_sun_open(5i)]
params[:store][:store_sun_closed(5i)]
To check if each parameter exists, I'm using two arrays:
days_of_week = [:mon, :tue, ..., :sun]
open_or_closed = [:open, :closed]
But, I can't seem to figure out how to dynamically create the params hash (the second key( with the array. Here's what I have so far:
days_of_week.each do |day_of_week|
open_or_closed.each do |store_status|
if !eval("params[:store][:store_#{day_of_week}_#{store_status}(5i)").nil
[DO SOMETHING]
end
end
end
I've tried a bunch of things including the eval method (as listed above) but rails seems to dislike the parentheses around the "5i". Any help is greatly appreciated!
You should be able to do
if params[:store]["store_#{day_of_week}_#{store_status}(5i)".to_sym]
Note that you were missing the ? on .nil? and that !object.nil? can be shortened to just object
Assuming this is a HashWithIndifferentAccess, you should be able to access it via string just as you could with a symbol. Thus:
days_of_week.each do |day_of_week|
open_or_closed.each do |store_status|
key = "store_#{day_of_week}_#{store_status}(5i)"
unless params[:store][key]
# DO SOMETHING
end
end
end
If it's not a HashWithIndifferentAccess then you should just be able to call key.to_sym to turn it into a symbol.

Get Model's Parameters in Ruby

I'm trying to build a generator in rails but I'm getting stuck at trying to access an existing model's parameters. Basically I want to do something like this:
# user is a model the has the parameters "id: integer, name: string, and email: string"
User.parameters.each do |parameter|
# do something with id, name, email
parameter.key
# do something with integer, string, string
parameter.value
end
Any ideas?
I think what you want is this
User.columns_hash.each do |key, value|
key
value.type
end
value.type will give you the type as a symbol. You can convert it to a string if you want it as a string
I think you are looking for attributes, rather than parameters.
user = User.first
user.attributes.each do |key, value|
# do something here with keys and values
puts key if key
puts value if value
end
Notice I'm grabbing an actual instance of the model as well as checking for nils (the if key/ if value part)
Got it! Need to use columns_hash like this:
Event.columns_hash.each {|k,v| puts "#{k} => #{v.type}"}
Credit to Getting types of the attributes in an ActiveRecord object

Searching in a subhash with Ruby on Rails

I have a hash of hashes like so:
Parameters: {"order"=>{"items_attributes"=>{"0"=>{"product_name"=>"FOOBAR"}}}}
Given that the depth and names of the keys may change, I need to be able to extract the value of 'product_name' (in this example "FOOBAR") with some sort of search or select method, but I cannot seem to figure it out.
An added complication is that Params is (I think) a HashWithIndifferentAccess
Thanks for your help.
Is this what you mean?
if params.has_key?("order") and params["order"].has_key?("items_attributes") then
o = params["order"]["items_attributes"]
o.each do |k, v|
# k is the key of this inner hash, ie "0" in your example
if v.has_key?("product_name") then
# Obviously you'll want to stuff this in an array or something, not print it
print v["product_name"]
end
end
end

Resources