Pluck returning duplicated results - ruby-on-rails

I am facing the following issue. My game object has two associated players, as we can see:
=> game.players.count
2
However, the pluck method is returning duplicated values:
=> game.players.pluck :name
["Alice", "Alice", "Bob", "Bob"]
Both Game and Player extend ActiveRecord::Base. I have absolutely no idea of what is really going on here.
Relevant gems:
rails 4.2.8
mysql2 0.3.21
Any clue about what could be going on? Thanks in advance.

I finally found out that the Player model has a default_scope that includes the translations from globalize3 gem:
default_scope { includes(:translations) }
I removed the default scope and it started working as expected.

Related

Ruby on rails ActiveRecord Relation not working?

I have an issue where my ActiveRecord::Relation isn't working I have 3 Db's Users,Games,Achievements The relation defined between them is such
Users
has_many :games
Games
belongs_to :user
has_many :achievements
Achievements
belongs_to :game
The problem is when i try to call
Game.where(:appid => game["appid"]).achievements.new
it gives me and error saying that
undefined method `achievements' for #<Game::ActiveRecord_Relation:0x730f9f8>
I am running on Ruby on Rails 4.1.8 and I have no clue why this is happening (I do have the belongs_to :game,index: true column in my Achievements table I can't think of why its 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.
Probably, you should select one model
Game.where(:appid => game["appid"]).first
and then get relational models
.achievements.new
The answer is in the exception. #where returns an ActiveRecord_Relation, not a Game, even if there is only one Game in the relation. So you really have an enumerable. i.e:
puts Game.where(:appid => game["appid"]).first.achievements.new
If you just want the first game that meets the criteria, you can use find_by
Game.find_by(:appid => game["appid"])
but I am not sure that's what you are looking for

ActiveRecord serialize not working properly with Hash column

I'm trying to store a Hash in a table column, using ActiveRecord's serialize method but I can't make it work. I'm using Rails 4.2.0 and RailsApi 0.3.1
This is my model:
class Agreement < ActiveRecord::Base
serialize :phone_numbers, Hash
end
phone_numbers is a text column like it's required.
Then in the console:
a = Agreement.new(phone_numbers: {"dario" => "12345"})
a.phone_numbers
=> "{\"dario\"=>\"12345\"}" #(Note this is a string, not a Hash as I would expect)
a.phone_numbers["dario"]
=> "dario" #(Not "12345" as I would expect)
Am I missing soemthing?? Thank you!
The behavior you're showing is consistent with the serialize call being wrong, either misnamed column, or missing entirely. Eg. https://gist.github.com/smathy/2f4536d3e59b7a52c855
You're showing the right code in your question, so either you didn't copy-paste that correctly, or perhaps it you haven't restarted your rails console since adding/correcting that serialize call?

mongoid as_document error

I am using mongoid with devise invitable,
after assigning roles to user I found the following error
"**undefined method `as_document' for Array **" , any suggestions ?
invitable = find_or_initialize_with_error_by(:email, attributes[:email])
invitable.attributes = attributes
# scope_id attribute does not set properly
invitable.roles.map {|r| r.scope_id = attributes[:roles_attributes]["0"][:scope_id]}
if invitable.persisted? && !invitable.invited?
invitable.errors.add(:email, :taken)
elsif invitable.email.present? && invitable.email.match(Devise.email_regexp)
invitable.invite!
end
Whats wrong I am doing ?
This is likely because as_document doesn't work against an array, only single objects.
This is a bug with Mongoid and has_many relationships.
The method 'as_document' has to be defined for has_many relationships, like it is defined for embeds_many relationships.
I am going to make a pull request to have this issue fixed, in the meantime you can define mongoid in your gemfile like so:
gem 'mongoid', :git => https://github.com/mrjlynch.git
That happened to me with MongoId 5.1.0 when, in one direction I had "embeds_many", and in the other direction I had "belongs_to".
From what I know, the reverse of embeds_many shall be embedded_in.
Changing the reverse relationship to embedded_in fixed that issue for me.
I have to admit, this is a very obscure error message.

Getting JSON for a model and its associations in Ruby on Rails

I have 3 models.
Venue :has_many :events
Events :has_many :event_dates
Im spitting out
events: <%= venue.events.to_json.html_safe %>
Which works correctly. But I also need an array of the event dates within each event. Im sure there is a very long winded way of doing this comparing ids, but im looking for an elegant solution.
Make Thanks.
When calling to_json on a model you can pass :include options to include associations (see the docs):
venue.events.to_json(:include => :event_dates)

Getting list of states/events from a model that AASM

I successfully integrated the most recent AASM gem into an application, using it for the creation of a wizard. In my case I have a model order
class Order < ActiveRecord::Base
belongs_to :user
has_one :billing_plan, :dependent => :destroy
named_scope :with_user, ..... <snip>
include AASM
aasm_column :aasm_state
aasm_initial_state :unauthenticated_user
aasm_state :unauthenticated_user, :after_exit => [:set_state_completed]
aasm_state : <snip>
<and following the event definitions>
end
Now I would like to give an administrator the possibility to create his own graphs through the AASM states. Therefore I created two additional models called OrderFlow and Transition where there order_flow has many transitions and order belongs_to order_flow.
No problem so far. Now I would like to give my admin the possibility to dynamically add existing transitions / events to an order_flow graph.
The problem now is, that I do not find any possibility to get a list of all events / transitions out of my order model. aasm_states_for_select seems to be the correct candidate, but I cannot call it on my order model.
Can anyone help?
Thx in advance.
J.
With version 3.0.18, you can should use ClassName.aasm.states
I don't understand how OrderFlow works with Order and Transitions, but I assumed you just included that to explain your scenario better.
ClassName.aasm_states_for_select gives you a list of states that is declared in the model.
For events in 3.1.1 I used Model.aasm.events.keys to get an array of event name symbols. In recent versions .map(&:name) won't do it for you.
also, not 100% sure what you're asking for, but if you want all the states and events declared for your model you could get those by calling Order.aasm_states and Order.aasm_events respectively.
A more elegant Ruby syntax can be used, as in this example in IRB below. You get all the allowable states in an array of symbols.
1.9.3-p0 :011 > ApprovalRequest.aasm_states.map(&:name)
=> [:created, :submitted, :rejected, :approved]
In version 5.4.0 this seems to now be an array, so we are back to
Model.aasm.events.map(&:name)

Resources