append a string to the params name - ruby-on-rails

In my rails app I am stuck with a situation where I need to add a string to the params name,
i.e, I have a params array params[:attended], but I need to have this as params[:attended_61] and _61 must be appended. 61 is the ID of an active record row object. I have that value in #sys.id. Then please tell me how I can convert params[:attended] to params[:attended_61]. Thank you.

Billy Chan is right, what you're trying to do sounds very strange and you should probably rethink your whole approach.
But if you must do such an odd thing, you could just do this:
params[:"attended_#{#sys.id}"] = params.delete(:attended)
Or, since params will be a HashWithIndifferentAccess, you could skip the symbolification:
params["attended_#{#sys.id}"] = params.delete(:attended)
# or even
params["attended_#{#sys.id}"] = params.delete('attended')
params is simply a method that returns a Hash, you can change that Hash as needed.

You can do that as given below.
params["attended_#{#sys.id}"]
Perfectly working !!

also you can add : to the params name to be like the natural params[:var] name and it will work well also to be like that
params[:"attended_#{#sys.id}"]

Related

Ruby on Rails - using a block parameter as a method call

I'm having trouble with a little Ruby on Rails I'm building and need some help.
I have a Table with 20+ Columns and a corresponding XML File which can be parsed as some sort of hash with a gem. Every key would be mapped to a column and every value would be a data record in said column.
The way I access a specific value in the already parsed XML file is:
filename["crs","inputkeyhere"]
which returns the value, for example "52" or whatever.
What I am trying to do is upload the file, parse it with the gem and give each column the corresponding value.
My table (or model) is called "Attributeset" and I already know how I can access every column:
#attributeset = Attributeset.new
#attributeset.attributes.keys
So my thought process was:
Iterate over all the keys
Pass every key into a block called |a|
Use the rails possibilty to set attributes by calling the corresponding #attributeset.
Set colum attribute to the corresponding xml key
So my code would go something like this:
#attributeset.attributes.keys.each do |a|
#attributeset.a=filename["crs",a]
end
But my problem is, that ruby thinks ".a" is a method and apparently does not evaluate "a" to the block parameter.
I've read through lambdas and procs and whatnot but didn't really understand how they could work for my specific situation.
Coming from bash scripting maybe my thinking might be wrong but I thought that the .a might get evaluated.
I know I can run the block with yield, but this only works in methods as far as I know..
Any help is appreciated.
Thanks and stay healthy,
Alex
Thanks for the input!
I wanted to make it as clean as possible, and not using any temporary hashes to pass arguments.
I've found the method
write_attribute
which can be used like this:
#attributeset.write_attribute(a, xmp["crs",a])
worked perfectly for me.
You can use []= method to set values dynamically:
#attributeset.attribute_names.each do |attribute|
#attributeset[attribute] = filename["crs", attribute]
end

In Rails 5, is there a way to modify the underlying params in a controller? Or give it a default?

In a Rails 5 controller, you can call params and it returns a hash of the parameters from the request.
But you can't modify the params that way. Because what you're modifying is a copy of the params hash values, not a reference to the underlying params.
params[:starting_value] ||= "abc" # doesn't work for my purposes
What you're supposed to do is store the values elsewhere.
#starting_value = params[:starting_value] || "abc"
But if a bunch of other places in the code expect params[:starting_value], then this solution might require some messy changes.
Is there a way to set the default value of a param in the controller? Or am I going to have to do it the slightly messier way.
I could also accomplish what I want with a redirect, but that isn't ideal either.
I think you're looking for the merge! method. Docs Here
params = params.merge!(:starting_value, 'abc)
It returns the original params with the new one merged in or overwritten. Be aware that merge without an exclamation mark does not modify in place. You need it to keep the changes.

How to use find method for composite primary keys in ruby on rails?

I have a table called SubElement.
It has two primary keys : Element_Code, Sub_Element_Code
In my view, when i try to do something like the following
<%
sub_element_model = Condition::SubElement
sub_element = #sub_element_code.nil? ? sub_element_model.new : sub_element_model.find(#sub_element_code)
if sub_element.persisted?
#element_code = sub_element.Element_Code
f.object.Sub_Element_Code = #sub_element_code
end
%>
I got an error after selected the sub_element_value like
["4"]: Incorrect number of primary keys for Condition::SubElement: [:Element_Code, :Sub_Element_Code]
How can i use the find method for two composite primary keys.
Update:
In the form, I have element_code field, sub_element_code and material. But everything should visible once the parent selected. With the help of some javascript I try to finish this. The Main problem of what I could not explain in detail is the form fields are creating by some helper file. It's a very large file and i cant change that. So I am looking for the alternative solution to change the find method for the two composite primary keys to get the value.
Not exactly sure what you're trying to do with the code above but you could use where:
sub_element_model.where(first_id: 3, second_id: 5).first
Your code doesn't look very conventional-ish however, perhaps if you described what you're trying to do SOers could help you come up with a neater solution :)
I myself never try using a multiple attribute primary key, but I believe that ActiveRecord is telling you that you are not using the correct number of primary keys in your find search.
Try something like
Model.find([first_part_of_primary_key, second_part_of_primary_key])
You should not be using find (which gets a single record by primary key - which you don't completely have), but rather where (which gets you a collection of records by any field(s) you want):
sub_element = #sub_element_code ?
SubElement.where(sub_element_code: #sub_element_code).first :
SubElement.new

Rails: Convert string to variable (to store a value)

I have a parameter hash that contains different variable and name pairs such as:
param_hash = {"system_used"=>"metric", "person_height_feet"=>"5"}
I also have an object CalculationValidator that is not an ActiveRecord but a ActiveModel::Validations. The Object validates different types of input from forms. Thus it does not have a specific set of variables.
I want to create an Object to validate it like this:
validator = CalculationValidator.new()
validator.system_used = "metric"
validator.person_height_feet = 5
validator.valid?
my problem right now is that I really would not prefer to code each CalculationValidator manually but rather use the information in the Hash. The information is all there so what I would like to do is something like this, where MAKE_INTO_VARIABLE() is the functionality I am looking for.
validator = CalculationValidator.new()
param_hash.each do |param_pair|
["validator.", param_pair[0]].join.MAKE_INTO_VARIABLE() = param_pair[1]
# thus creating
# "validator.system_used".MAKE_INTO_VARIABLE() = "metric"
# while wanting: validator.system_used = "metric"
# ...and in the next loop
# "validator.person_height_feet".MAKE_INTO_VARIABLE() = 5
# while wanting: validator.person_height_feet = 5
end
validator.valid?
Problem:
Basically my problem is, how do I make the string "validator.person_height" into the variable validator.person_height that I can use to store the number 5?
Additionally, it is very important that the values of param_pair[1] are stored as their real formats (integer, string etc) since they will be validated.
I have tried .send() and instance_variable_set but I am not sure if they will do the trick.
Something like this might work for you:
param_hash.each do |param, val|
validator.instance_eval("def #{param}; ##{param} end")
validator.instance_variable_set("##{param}", val)
end
However, you might notice there's no casting or anything here. You'd need to communicate what type of value each is somehow, as it can't be assumed that "5" is supposed to be an integer, for example.
And of course I probably don't have to mention, eval'ing input that comes in from a form isn't exactly the safest thing in the world, so you'd have to think about how you want to handle this.
Have you looked at eval. As long as you can trust the inputs it should be ok to use.

how to parse multivalued field from URL query in Rails

I have a URL of form http://www.example.com?foo=one&foo=two
I want to get an array of values ['one', 'two'] for foo, but params[:foo] only returns the first value.
I know that if I used foo[] instead of foo in the URL, then params[:foo] would give me the desired array.
However, I want to avoid changing the structure of the URL if possible, since its form is provided as a spec to a client application. is there a good way to get all the values without changing the parameter name?
You can use the default Ruby CGI module to parse the query string in a Rails controller like so:
params = CGI.parse(request.query_string)
This will give you what you want, but note that you won't get any of Rails other extensions to query string parsing, such as using HashWithIndifferentAccess, so you will have to us String rather than Symbol keys.
Also, I don't believe you can set params like that with a single line and overwrite the default rails params contents. Depending on how widespread you want this change, you may need to monkey patch or hack the internals a little bit. However the expeditious thing if you wanted a global change would be to put this in a before filter in application.rb and use a new instance var like #raw_params
I like the CGI.parse(request.query_string) solution mentioned in another answer. You could do this to merge the custom parsed query string into params:
params.merge!(CGI.parse(request.query_string).symbolize_keys)

Resources