Has_many returns an array instead of the ActiveRecord class

I am following OmniAuth railscasts and trying to implement the same with authlogic + facebook instead of devise + twitter, as shown in railscast.

Maybe my understanding of has_many is still not very good, but in railscasts ryan has the following code in AuthenticationsController

  def create auth = request.env["rack.auth"] current_user.authentications.find_or_create_by_provider_and_uid(auth['provider'], auth['uid']) flash[:notice] = "Authentication successful." redirect_to authentications_url end 

In my implementation, current_user.authentications returns an array [] , how can I call find_or_create_by_provider_and_uid in the array?

Is my implementation wrong? Does has_many not return an array?

The error I get is that I call find_or_create_by_provider_and_uid on the nil object.

current_user.authentications is zero because the user does not have any authentications yet.

+6
source share
1 answer

The array is actually an instance of AssociationProxy , which delegates all method calls to the internal object, which is an array in the case of the has_many association (also see this question ). This means that you should be able to name magic methods such as find_or_create_by_provider_and_uid , as well as areas, etc. It’s just fine on it.

I found this question because I came across a similar problem: for some reason I could not call ActiveRecord::Relation#klass to find out the model class:

 post.comments.klass # => NoMethodError 

But first by calling relation , you can get a regular instance of ActiveRecord::Relation :

 post.comments.relation.klass # => Comment 
+5
source

Source: https://habr.com/ru/post/889650/


All Articles