Rails 4.1 Activerecord::Relation Is No More Like Array

Ruby on rails ActiveRecord Relation not working?

You are getting an association here:

 Game.where(:appid => game["appid"])

... this is realized as an array of objects (even if the sql returns no records, then it is still an array, although it is empty).

You need to select one of them ... probably the first, like this:

 Game.where(:appid => game["appid"]).first.achievements.new

Or you can run through the values:

 Game.where(:appid => game["appid"]).each { |game| game.achievements.new }

or some such.

Shift not working after upgrading rails to 4.1. Attempting to remove first item from array. No longer getting array to use shift on

Yes, in Rails >= 4.0 even after you call all on relation, it isn't converted to array object. If you really need 'pure' array, you have to do it manually, calling to_a.

Rails Scope is returning an array instead of an ActiveRecord_Relation

This worked for me:

#models/agency.rb
class Agency < ActiveRecord::Base
has_many :contacts, dependent: :destroy
scope :by_contact_name, -> (name){joins(:contacts).merge(Contact.by_name(name))}
end

#models/contact.rb
class Contact < ActiveRecord::Base
belongs_to :agency
scope :by_name, -> (full_name){where("CONCAT(first_name,' ',last_name) LIKE ?", "%#{full_name}%")}
end

Usage:

@agencies = Agency.by_contact_name("joe s") 

ActiveRecord does not convert array in string to array

I'm not sure which commit between 4.1.10 and 4.2.1 introduced this behaviour but it's not a bug as it is well documented here. In particular,

If class_name is specified, the serialized object must be of that class on assignment and retrieval. Otherwise SerializationTypeMismatch will be raised.

With Rails 4, Model.scoped is deprecated but Model.all can't replace it

It seems that where(nil) is a real replacement of scoped, which works both on Rails 3 and 4. :(

Rails 4 Sum by Model Method

On Rails 4.1

If goal_ydt is a column in the users table:

@users.sum(:goal_ydt)

If goal_ydt is a method in User class:

@users.to_a.sum(&:goal_ydt)

How do I create a base class that abstracts a has and belongs to many relationship in Rails 4.1

Look into a concept called concerns, introduced in Rails 4. Abstracting a class inherited from ActiveRecord::Base is a recipe for trouble.

A good explanation How to use concerns in Rails 4.

ActiveRecord.find(array_of_ids), preserving order

The answer is for mysql only

There is a function in mysql called FIELD()

Here is how you could use it in .find():

>> ids = [100, 1, 6]
=> [100, 1, 6]

>> WordDocument.find(ids).collect(&:id)
=> [1, 6, 100]

>> WordDocument.find(ids, :order => "field(id, #{ids.join(',')})")
=> [100, 1, 6]

For new Version
>> WordDocument.where(id: ids).order("field(id, #{ids.join ','})")

Update:
This will be removed in Rails 6.1 Rails source code



Related Topics



Leave a reply



Submit