I have a Model that is called teams.
When I do Teams.account_ids it returns something like:
[{"_id"=>"145952912234658", "_type"=>"Page"},
{"_id"=>"465641870160985", "_type"=>"Account"}]
Lets say I want to get all Teams that have one specific account id regardless of its _type.
Something like:
Team.where(some_id.in => account_ids.map{|k| k["_id"))
You can use multi-keys to effectively ignore the array when searching and then use the standard "key inside a hash" notation to look at the _ids:
Teams.where('account_ids._id' => { :$in => array_of_ids })
Related
In my application, the session hash can contain the keys sort and ratings (in addition to _csrf_token and session_id), depending on what action a user takes. That is, it can contain both of them, either one of them, or neither, depending on what a user does.
Now, I wish to call redirect_to in my application and, at the same time, restore any session information (sort or ratings) the user may have provided.
To do this, I want to insert whatever key-value session has currently got stored (out of sort and ratings) as query parameters in my call to redirect_to. So, the path might look something like /movies?sort=...&ratings=....
I don't know how to write the logic for this. How can I do this? And how do I go about selectively inserting query parameters while calling redirect_to? Is it even possible to do this?
Any help is greatly appreciated. Thank you in advance.
First just compose a hash containing the parameters you want - for example:
opts = session.slice(:sort, :ratings)
.merge(params.slice(:sort, :ratings))
.compact_blank
This example would contain the keys :sort, :ratings with the same keys from the parameters merged on top (taking priority).
You can then pass the hash to the desired path helper:
redirect_to foos_path(**opts)
You can either just pass a trailing hash option or use the params option to explitly set the query string:
irb(main):007:0> app.root_path(**{ sort: 'backwards' })
=> "/?sort=backwards"
irb(main):008:0> app.root_path(params: { ratings: 'XX' })
=> "/?ratings=XX"
irb(main):009:0> app.root_path(params: { })
=> "/"
An empty hash will be ignored.
If your calling redirect_to with a hash instead of a string you can add query string parameters with the params: key:
redirect_to { action: :foo, params: opts }
If you're working with an arbitrary given URL/path and want to manipulate the query string parameters you can use the URI module together with the utilities provided by Rack and ActiveSupport for converting query strings to hashes and vice versa:
uri = URI.parse('/foo?bar=1&baz=2&boo=3')
parsed_query = Rack::Utils.parse_nested_query(uri.query)
uri.query = parsed_query.except("baz").merge(x: 5).to_query
puts uri.to_s # => "/foo?bar=1&boo=3&x=5"
I'm trying to get a a bidimensional hash from a activerecord group request like this.
MachineFailure.group("machine.key", "failure.name").sum("timestampdiff(hour, machine_failures.created_at, closed_at)")
this returns me a hash like:
{["R01", "Corrective Maintenance"]=>3, ["R01", "Auto reboot"]=>8}
when I actually need something like this:
{"R01" => {"Corrective Maintentance" => 3, "Auto reboot" => 8}}
thx
This answer is exactly what you need.
In short, you need to map the hash that is returned after the call to the database.
I'm trying to query an array of signups. Each Signup has a field on it twitter.
The field is an array and at present will only have two items, but can also only have one. The three possible outputs from calling Signup.twitter are:
Signup.twitter => ["No Twitter", "randomhandle"]
Signup.twitter => ["No Twitter"]
Signup.twitter => ["randomhandle"]
I'm trying to use a .where query to only return me handles that have a randomhandle in. If they return ["No Twitter", "randomhandle"] I still want that record to be returned though.
Any help must appreciated,
Thanks.
Try array search methods, like find_all (select is the same) or reject (http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-find_all)
Absolutely agree with the previous answer, but I would do it in 'positive' way, rather than 'negative' so as to keep it clear:
Signup.all.find_all do |signup|
# Use Array.wrap or protect it from `undefined method for nil class`
"randomhandle".in? Array.wrap(signup.twitter)
end
Ultimately, you can do whatever you want.
In case if the twitter field is association you can use where directly:
Signup.where(twitter: Twitter.where(name: "randomhandle"))
Check http://guides.rubyonrails.org/active_record_querying.html
This should work:
only_twitter_users = Signup.all.reject do |signup|
signup.twitter == ["No Twitter"]
end
I think the best way for me to explain this question is with example. Here is a simple method with a hash:
def getValues(table)
allColumns = {
'User' => ['first_name', 'last_name'],
'Vehicle' => ['make', 'model', 'id'],
}
end
I am trying to pass in the table and based on that table return a range of values. I would like to know what would be (performance-wise) the best way to accomplish this. Is it using a switch statement, if/else, some sort of loop? If you come up with an answer, please be as kind to include an example so that I may understand better.
I suggest you to rename the parameter first, maybe to table_name or something more descriptive.
Second it is kind of a convention in ruby to use method names separated by _, and avoid using camelCase as another languages.
Third, i would put the list on a constant variable or something, and just reference it inside the method.
Then you can look up the values of some hash based on a key just by using hash[key].
LIST = {
'User' => ['first_name', 'last_name'],
'Vehicle' => ['make', 'model', 'id'],
}
def get_values(table_name)
LIST[table_name]
end
Hash lookup by key is probably one of the most performant operations you could do with a collection, so there is no need to worry about it.
I am setting up an API.
The client (using HTTParty) posts this to the API:
{:body =>
{
:product=> {:description=>"some text", :cost => "11.99"},
:brand=> {:name=>"BrandName", :etc =>"hey"}
}
}
The server/api receives the post.
Now, if I access params[:brand] I get:
{"name"=>"BrandName", "etc" =>"hey"}
If I do this:
Brand.new(params[:brand])
Then I get a new Brand object with the "name" and "etc" attributes populated correctly.
However, if I try to access params[:brand][:name], I just get nil
Any ideas?
Thanks.
Use params[:brand]["name"] or params["brand"]["name"]
Hash keys can be any sort of object. Common rails practice is to use symbols as hash keys, but when translated from JSON, the keys are likely to be strings.