I want to compare a param extracted from a link to the list of data present in column...
I am using pluck to generate a array of list(in controller) but not getting any success in comparing it
any method that I can fetch records in model and compare with param in controller or model
as passing controller instances in model seems inappropriate to me
Initially i am trying fetching and comparing in controller..
#abc=Group.pluck(:group_token)
what I tried to do before is defined group_fetch method in model and used it in controller to check condition but I was not able to compare param which comes frome url dynamically
def self.group_fetch
Group.find_by group_token: 'UuzsG7NMvYFzxwPDdYgLxJbF'
end
what will be the best way to fetch db column and compare it with the link param
You can use the exists? method which pretty much does what it says.
Group.exists?(group_token: params[:token])
You can use include? to check if the param is in the list. For example:
def your_method
list = Model.pluck(:attribute)
list.include?(params[:your_param])
end
Related
I have 3 models as category, posts and comments. I want to display posts and number of comments in the category page.
category.(:id)Post.(:id).comments.count will return the number of comments.
But how should I pass those parameters from category controller? I'm also trying to write the jbuilder view for the same.
or Can I do something like this directly from jbuilder view?
#this work
json.number #category.posts.count
#this one doesn't work
json.number #category.posts.comments.count
json.number #category.posts.count it works but
json.number #category.posts.comments.count this does not.
You can test in rails console.. like #category.posts.comments.count.
it may throw error like
NoMethodError: undefined method 'comments' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Post:0x0000000920b058>
This happens because #category.posts returns a collection not Post object.
One possible solution is
#category.posts.map {|post| [post, post.comments.count] }
This gives you the total count of comments per post in array. This may not be exactly what you wanted but you may modify to meet your requirement.
The easiest way to pass parameters from the controller to a view you are going to present is using the # (instance variable). Therefore you can pass:
#count = <your code above>
#all_posts = <your post code>
If you have alot of different parameters, just create an object to pass them across in:
#post_info = {
count: <your code above>,
all_posts: <your post code>
}
And then retrieve them in your view using #post_info[:count] and #post_info[:all_posts]
I have to use a query like this :
query = Enc.joins(:rec).group("enc.bottle").
select("enc.bottle as mode, count(rec.id) as numrec, sum(enc.value) as sumvalue")
That I use with :
#enc = ActiveRecord::Base.connection.select_all(query)
To get the data, I've to do #enc.rows.first[0] (it works)
But #enc.rows.first["mode"] doesn't work ! Because each row of #enc.rows contains array.. not a map with the name of each field.
Maybe select_all is a wrong method.
Does it exist another method to get the data with the name of field ?
Thank you
EDIT
If you can associate a model with the query, then there's no need for the generic select_all method. You can use find_by_sql like this:
Enc.find_by_sql(query).first.mode
# => testing
Note that you will no be able to see the aliases when inspecting the results, but they are there. Also, the convention is to use plural names for the tables. You might find it easier to just sticks with the defaults.
Here's what's happend: I have gone and pulled a large amount of data from an API. This is nice, but it includes a lot of results.
When I do a result.find(id: api_id) I get all the results like find was never performed. #where does not work either. I'm assuming this is because its not extending from Active Model.
Key Question: How do I find, say, the name of a particular object in an active resource collection?
Object.find(id: api_id) in active resource is essentially doing an api request as in (uri_of_api)/objects/:api_id)
But the :find method on an array is a different aninmal. You can look up the array 'find' method here... http://www.ruby-doc.org/core-2.1.1/Enumerable.html#method-i-find
The correct format would be...
result.find{|rec| rec.id == api_id}
I'm serializing many attributes on a model Page as hashes.
Because of the high number of attributes, I've taken a meta-programming approach and want to use .send() to iterate through a collection of attributes (such that I don't have to type out an update action for each attribute.
I've done something like this:
insights.each do |ins|
self.send("#{ins.name}=", {(Time.now) => ins.values[1]['value'].to_f})
self.save
end
The problem is that this obviously overwrites the whole serialized column, whereas I wish to add this as an element to the serialized hash.
Tried something like this:
insights.each do |ins|
self.send("#{ins.name}[#{Time.now}]=", ins.values[1]['value'].to_f)
self.save
end
But get a NoMethodError: undefined method page_fan_adds_unique[Mon Aug 13 13:31:58 -0400 2012]=
In the console I'm able to do Page.find(5).page_fan_adds_unique[Time.now]= 12345 and save it as an additional element to the hash as expected.
So how can I use .send() to save an additional element to a serialized hash? Or is there some other approach? Such as using update_attribute or another method? Writing my own? Any help is appreciated, even if the advice is that I shouldn't be using serialization for this.
I'd do :
self.ins.name.send(:[]=, key, value)
I need to test if an instance variable in my controller contains a specific value. I think .include? would be the way to do it but that doesn't seem to work.
My code looks something like this:
#names=Model.find_by_sql("select name from ...")
if #names.include?(params[:name])
...
end
The if statement somehow allways evaluates to true.
Thanks
Firstly, find_by_sql is not a good way to do. find_by_sql will return you an object of class Model. Whereas params[:name] is most likely a string. The following should work:
Model.find(:all, :conditions => 'specify conditions here').map(&:name).include?(params[:name])
The results of find_by_sql will be (from the docs):
an array with columns requested encapsulated as attributes of the model you call this method from.
You need to search within the results.