ruby - Rails CollectionProxy randomly inserts in wrong order -



ruby - Rails CollectionProxy randomly inserts in wrong order -

i'm seeing weird behaviour in models, , hoping shed lite on issue.

# user model class user < activerecord::base has_many :events has_and_belongs_to_many :attended_events def attend(event) self.attended_events << event end end # helper method in /spec-dir def attend_events(host, guest) host.events.each |event| guest.attend(event) end end

this, reason inserts event id 2 before event id 1, so:

#<activerecord::associations::collectionproxy [#<event id: 2, name: "dummy-event", user_id: 1>, #<event id: 1, name: "dummy-event", user_id: 1>

but, when seemlingly random - instance alter attend_event method so:

def attend_event(event) self.attended_events << event p self.attended_events # random puts statement end

it gets inserted in right order.

#<activerecord::associations::collectionproxy [#<event id: 1, name: "dummy-event", user_id: 1>, #<event id: 2, name: "dummy-event", user_id: 1>

what not getting here?

unless specify order on association, associations unordered when retrieved database (the generated sql won't have order clause database free homecoming things in whatever order wants)

you can specify order doing (rails 4.x upwards)

has_and_belongs_to_many :attended_events, scope: -> {order("something")}

or, on before versions

has_and_belongs_to_many :attended_events, :order => "something"

when you've inserted object may see different object - here seeing loaded version of association, array (wrapped proxy)

ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-4.1

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -