w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
ActiveRecord Relation error
The usage of will_paginate is slight different than Kaminari. You should do: @users = User.order('name').paginate(page: params[:page], per_page: 5)

Categories : Ruby On Rails

How to manage relation using PHP-activerecord
Try making sure that the name of the file matches the name of the class in case also. See the solution to my issue Apparently, libraries too have to be named accordind to the UCfirst naming convention.

Categories : PHP

RoR extend ActiveRecord::relation with undestroy_all
When you call ActiveRecord::Relation.extend Track::TrackRelation you are mixing the Track::TrackRelation methods into ActiveRecord::Relation as class methods. What you want to do is mix in those same methods as instance methods. You can do that using include rather than extend. However Module#include is private. So one way to achieve what you want is: ActiveRecord::Relation.send(:include, Track::TrackRelation)

Categories : Ruby On Rails

Serializing ActiveRecord::Relation objects for storage
I'm not sure it is really a good solution, but you can save your AREL as a string and then evaluate it like that: For example, you want to save Bid.first class Report < ActiveRecord::Base attr_accessible :arel def arel_eval args = @arel.split('.') model = args.shift.constantize args.inject(model) {|mod, met| mod.send(:#{met})} end end report = Report.new(arel: "Bid.first") report.arel_eval

Categories : Ruby On Rails

Building an ActiveRecord relation without having it execute the query
When you run commands in the console, it automatically adds something similar to .inspect at the end to display the results of the command. For instance (this is in my app that I'm working on right now): irb(main):061:0> Job.where(id: 251000) Job Load (3.8ms) SELECT "jobs".* FROM "jobs" WHERE "jobs"."deleted_at" IS NULL AND "jobs"."id" = 251000 => [#<Job id: 251000, {...}>] So, your first line of code is just fine and would not normally execute the query, but since you were running it in the console it executes immediately so that it can display the results for you. One way to get around this is to add ; nil to the end of the command, that way the console won't attempt to display the results (it'll just display nil as the result of that line. IE: irb(main):062:0> J

Categories : Ruby On Rails

ActiveRecord Relation size strange behavior
That's how ActiveRecord Relation works. You can convert it into an array and do a size on it. a = Stat.aggregated.to_a #in other place if a.size > 0 'do stuff' else 'do other stuff' end

Categories : Ruby On Rails

rails update_all for ActiveRecord Relation using 'having' don't work
update_all only takes the constraints from your query and ignores the group and having clauses. Here is the source code of update_all def update_all(updates) ..... # HERE IS THE RELEVANT CODE # It extracts only the constraints, limit and order clauses. It ignores the rest stmt.take(arel.limit) stmt.order(*arel.orders) stmt.wheres = arel.constraints ..... end I guess you would have to do it in two steps, execute your query with the having clause and get the list IDs for the 50 records that match and then do an update_all on these records using an IN clause

Categories : Mysql

Using the Map function to remove a object from an activerecord::relation
If I understand clearly you want only the completed checklists Basically you must return the checklist when it's true and nil when it's not, then eliminate the nils in resulting array with compact... which is the work of select checklists.map do |checklist| # .... checklist unless not_completed end.compact or more concisely : checklists.select do |checklist| # .... !not_completed end

Categories : Ruby On Rails

Converting an array of objects to ActiveRecord::Relation
How can I convert an Array of objects to an ActiveRecord::Relation? Preferably without doing a where each time. You cannot convert an Array to an ActiveRecord::Relation since a Relation is just a builder for a SQL query and its methods do not operate on actual data. However, if what you want is a relation then: for ActiveRecord 3.x, don’t call all and instead call scoped, which will give back a Relation which represents the same records that all would give you in an Array. for ActiveRecord 4.x, simply call all, which returns a Relation. When running a def self.subjects type method on an ActiveRecord::Relation, how do I access that ActiveRecord::Relation object itself? When the method is called on a Relation object, self is the relation (as opposed to the model class it’s

Categories : Ruby On Rails

Rails 3.2: undefined method for []:ActiveRecord::Relation
Change this line has_many :attributes, :dependent => :destroy to has_many :category_attributes, :dependent => :destroy, :class_name => 'Attribute' along with rest attr_accessible etc. to avoid conflict with build in attributes rails method

Categories : Ruby On Rails

NoMethodError - undefined method 'find_by' for []:ActiveRecord::Relation
I believe find_by was introduced in rails 4. If you are not using rails 4, replace find_by by a combination of where and first. relationships.where(followed_id: other_user.id).first You can also use the dynamic find_by_attribute relationships.find_by_followed_id(other_user.id) ASIDE: I suggest you change your following? method to return a truthy value rather than a record (or nil when no record is found). You can do this by using exists?. relationships.where(followed_id: other_user.id).exists? One big advantage of this is it doesn't create any object and just returns a boolean value.

Categories : Ruby On Rails

ActiveRecord access relation gives stack level too deep
What is happening is that your image function keeps calling itself endlessly if image is set: def image if self.image return self.image ... end You get that error when it has called itself enough to fill up the stack.

Categories : Ruby On Rails

Rails ActiveRecord - How do I determine the owner in a polymorphic relation?
class Tax belongs_to :taxable, :polymorphic => true # tax table needs taxable_type taxable_id end class Company has_one :tax, :as => :taxable end class Person has_one :tax, :as => :taxable end Tax.first.taxable

Categories : Ruby On Rails

NoMethodError: undefined method `to_csv_test' for ActiveRecord::Relation
I'm actually confused on what you're trying to do here. Why act on this instance to get all the orders into a CSV? Maybe this is what you want instead? Spree::Order.instance_eval do def to_csv_test(options = {}) CSV.generate(options) do |csv| csv << column_names all.each do |order| csv << order.attributes.values_at(*column_names) end end end end Also, here is a better explanation of instance_eval and class_eval http://www.jimmycuadra.com/posts/metaprogramming-ruby-class-eval-and-instance-eval

Categories : Ruby On Rails

Rails - undefined method `user' for ActiveRecord::Relation
Your problem is that you are calling an instance method on a list of objects. @data = @user.datas.includes(:user).includes(:images) This is actually an array of Data objects belonging to the user's instance @user. To solve this, you can get the first element of the list and get its user: = render 'users/header', :user => @data.first.user But you should know that all the @variables are shared between the controller's action, the view and the invoked partials. With this in mind, you will notice that you can simply do the following: # in datas/show.html.haml = render 'users/header' # in users/_header.html.haml # you can use the @user variable as your wishes = @user

Categories : Ruby On Rails

undefined method `user_id' for #
where is returning an ActiveRecord::Relation object. Because where(:mgmt => current_user.company) could return 0, 1, or Many records, you have to tell the query what you'd like from it. Try: myestate = Estate.where(:Mgmt => current_user.Company).first @managements = User.where(:id => myestate.user_id) Getting familiar with AREL and how it works is highly recommended. You can find great info on the github page or the Active Record Query Guide

Categories : Ruby

Couldn't find User with id=#
Take a look at the view file for the edit command, so edit.html.erb. You're likely trying to call something on a join model, instead of the actual object you are trying to display.

Categories : Ruby On Rails

Rails 4: Joins in ActiveRecord relation lambas not include when doing a join
I've encountered a similar problem. Any joins specified in a lambda for a has_many are silently ignored. I found this in the Rails issues that solves the problem for me: https://github.com/rails/rails/pull/11518 The author mentions the problem occurring when there is an order clause but I think this muddies the water - it makes no difference whether there is an order clause or not. I cannot say whether this is a bug or intended behaviour but I suspect the former.

Categories : Ruby On Rails

ActiveRecord: Choose results based on value of a field in another model with a belongs_to relation
You have to use intermediate relation Property or you need to define new relation between Tracker and Branch Tracker.joins(:property).merge(Property.where(branch_id: [0,1]))

Categories : Ruby On Rails

Ruby ActiveRecord: DEPRECATION WARNING: Relation#find_in_batches with finder options is deprecated
Change limit: limit for batch_size: limit EDIT Since you need a limit and your batch is based on id, i think you can do something like: Person.where("id < ?", (start_index + limit)).find_each(start: start_index) do |person|

Categories : Ruby

Rabl for a nested hash of ActiveRecord collections
if i were you i will not even care to go to rabl template for this because what your are creating with this code: @data = { cities: City.limit(2), countries: Country.limit(2), states: State.limit(2), version: 1000 } is the final output , not the individual components. you can just replace this with: render :json => { :data => { cities: City.limit(2).map{ |c|{:id => c[:id] }, countries: Country.limit(2).map{ |c|{:id => c[:id] }, states: State.limit(2).map{ |c|{:id => c[:id] }, version: 1000 } } its not a best use case for rabl , but if you still want it to load via rabl this below code in the get_data.json.rabl will do just fine. node :data do { :version_number => @data[:version_number], :country => @data[:count

Categories : Ruby On Rails

Does an ActiveRecord after_save call slow down the controller?
This will not happen asynchronously unless you specifically use a queue like Resque or Sidekiq or some other background job processing alternative.

Categories : Ruby On Rails

Rails ActiveRecord Query: Too slow unless I split it into 2 queries. Why?
if you are using rails 4 then query chaining is possible. else what you can do is select the required field as you need to show. and also do the proper indexing for search fields but make sure before and after adding the index please check you performance. or another option is write a required sql query. and use it by find_by_sql method in rails.

Categories : SQL

Rails - Heroku Postgresql SQL Error - Works on Local SQLite - Error "ActiveRecord:Invalid Relation"
Your SQL ends up with this in it: status1 is 't' and that's invalid: is is only used with is null, is distinct from, and similar constructs. You should upgrade to a more modern syntax and leave most of the work to ActiveRecord: @table2_items = @table1var.table2_items .where(:status1 => true, :status2 => nil) .where('start_datetime > ?', Time.now) .order(:field_id, :created_at) That leaves most of the "how do I compare things?" logic up ActiveRecord and is a bit easier to read as the placeholders and their values aren't separated from each other. Once you have this problem sorted out, you really should install PostgreSQL in your development environment so that you're developing and deploying on th

Categories : Postgresql

Redis Hash on C# is incredibly slow in WCF Service
My issue was with the class I was using as the context for the Redis client. The class was an entity model generated using the old version of the entity framework with Object Context. The way the entities were being generated was causing the ServiceStack.Redis client to have to do a ton of work to deserialize the objects coming back from Redis. The entities navigation property's set methods have calls to InitializeRelatedCollection() which were being called every time the json parser had to deserialize an object coming back through the Redis client. Switching to a simpler object without the navigation properties worked fine and brought the times back to numbers I expected in line with my other tests. The reason I did not see this slow down in the ASP.NET Web API was because the entitie

Categories : C#

Convert Ruby mapping statement to ActiveRecord query?
It seems that your models are like this: Role has_many :users User belongs_to :role has_one :manager, :class => 'User' In the case, just inner joining the tables shall bring back the results you are after: SELECT roles.* FROM roles INNER JOIN users u ON u.role_id = roles.id INNER JOIN users m ON m.id = u.id This query can be translated to something like this: Role.joins(:users => :manager)

Categories : Ruby On Rails

Convert a hash to NSString?
When you see something output as "<" 8 hex digits space .... ">", it's the result of logging a NSData object (NSLog(@"%@", myDataObject);). So I believe what you have is not an NSUInteger, but a NSData * object. There is no built in method to convert between strings and data, you need to do it in code: - (NSString *)dataToString:(NSData *)data { NSUInteger len = [data length]; NSMutableString *str = [NSMutableString stringWithCapacity:len*2]; const uint8_t *bptr = [data bytes]; while(len--) [str appendFormat:@"%02.2x", *bptr++]; return str; } If this works, you can write your own stringToData method reversing the above, if needed.

Categories : Iphone

How to convert hash in to an array?
So what you have there is a deeply-nested object graph. To make an array out of it, you'd probably use for-in to loop through the properties of the object at each level and use the values to build up an array. It's not remotely clear from the question what you might want that array to look like, so I can't really help further. Here's what a for-in loop looks like: var key; for (key in obj) { // Here, `key` will have each property name; to get // that property's value, use obj[key] } So for example: var obj = { a: 1, b: 2 }; var key; for (key in obj) { console.log(key + "=" + obj[key]); } ...will output a=1 b=2 (the order isn't guaranteed).

Categories : Javascript

How to convert hash into request url?
url_for(hash) in your case: url_for(:action=>'index', :controller=>'users', :search=>'John') returns /users?search=John host_name will be added automatically. If you explicitly want to add host_name you can pass host: key in your hash

Categories : Ruby On Rails

convert "denormalised" hash
Its hard to gauge exactly what you want to do, but from what I can gather from you question this should work; rawfile_hash.each do |key, value| # if a new key integer, then create a new record # ie: primer3_output = Primer3Output.new key.gsub!(/_d+/,"") # simple regex if primer3_output.class.accessible_attributes.include?(key) primer3_output.send("#{key}=", value) end end EDIT Re: your comment below — You could include an extra column in the db and find or create the record by that value, that way you can still sort by it. Something like this; i = key.gsub(/[^0-9]/,"").to_i key = key.gsub(/_d+/,"") Primer3Output.find_or_create_by(:i => i)

Categories : Ruby On Rails

Obtaining the hash of a file using the stream capabilities of crypto module (ie: without hash.update and hash.digest)
From the quoted snippet in the question: [the Hash class] It is a stream that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the read() method to get the computed hash digest. So what you need to hash some text is: var crypto = require('crypto'); // change to 'md5' if you want an MD5 hash var hash = crypto.createHash('sha1'); // change to 'binary' if you want a binary hash. hash.setEncoding('hex'); // the text that you want to hash hash.write('hello world'); // very important! You cannot read from the stream until you have called end() hash.end(); // and now you get the resulting hash var sha1sum = hash.read(); If you want to get the hash of a file, the best way is create a ReadStream from th

Categories : Node Js

Convert XML string to hash in Rails
You can try this below:-- require 'active_support/core_ext/hash/conversions' Hash.from_xml " <Result> <success> true </success> </Result>".gsub(" ", "").downcase Output :-- what I got {"result"=>{"success"=>"true"}} Thanks

Categories : Ruby On Rails

convert csv in perl hash of arrays
Something like: while ( my $line = readline($fh) ) { chomp $line; my ( $emp_no, $birth_date, $first_name, $last_name, $gender, $hire_date ) = split /,/, $line; push @{ $employee->{emp_no} }, $emp_no; #etc. }

Categories : Perl

Javascript. Convert MD5 hash into an integer
That looks like a hexadecimal number, so you could try using the parseInt function and pass in a base of sixteen: var num = parseInt(string, 16);

Categories : Javascript

In a file/array, search for hash key, and replace it with the hash value, do this for all hash keys/values
You exhaust your file the first time through your loop using the initial $find and $replace key/value pair. There are two potential solutions: Open the file for reading during each iteration of your while loop (expensive) Move the foreach loop to the outside of the while and iterate the hash each time (less expensive) example: REPLACE: for my $line (@gtfarray) { while(my ($find, $replace) = each %hash) { if($line =~ s/$find/$replace/g) { push @newgtf, $line; next REPLACE; # skip to next iteration } } # if there was no replacement, push the old line push @newgtf, $line }

Categories : Perl

Convert collection of hash maps to a csv file
Use data.json to convert the json to a sequence of clojure maps. Use map destructuring to convert to a sequence of strings: (map #(let [{a :a b :b c :c d :d} %] (str a "," b "," c "," d, " ")) <your sequence of clojure maps>). Dump the sequence of strings to a file

Categories : Clojure

How to convert hash of hashmaps to json in java
use new JSONObject(map); Other functions you can get from its documentation http://www.json.org/javadoc/org/json/JSONObject.html

Categories : Java

Convert JSON to string or hash in ruby
Your incoming string in JSON would look like: {"id":"ABC","account_id":"123","first_name":"PEUS"} After parsing with JSON it's the hash: {"id"=>"ABC", "account_id"=>"123", "first_name"=> "PEUS" } So, I'd use: hash = {"id"=>"ABC", "account_id"=>"123", "first_name"=> "PEUS" } hash['id'] # => "ABC" Here's a more compact version: require 'json' json = '{"id":"ABC","account_id":"123","first_name":"PEUS"}' hash = JSON[json] hash['id'] # => "ABC" Note I'm using JSON[json]. The JSON [] class method is smart enough to sense what the parameter being passed in is. If it's a string it'll parse the string. If it's an Array or Hash it'll serialize it. I find that handy because it allows me to write JSON[...] instead of having to remember whether I'm parsing or using

Categories : Ruby

why when creating a hash do you convert text to byte
Hash functions operate on byte streams (or arrays). This is just how they are defined. Text however is in most cases Unicode and thus needs to be transformed into a particular UTF first before you have a byte representation you can work with.

Categories : C#

Routing for root gives "can't convert String into Hash"?
Although both should work based on the documentation (http://guides.rubyonrails.org/routing.html). Try changing: root 'election#new' to: root to: 'elections#new' # elections (pluralized) for controller name. Update: So root 'elections#new' works as specified in the linked doc in rails 4.0 but not in Rails 3.2'. Rails 3.2 requires the to: option.

Categories : Ruby On Rails



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.