Omn*_*ent 6 has-many railscasts ruby-on-rails-3
我正在关注OmniAuth railscast并尝试使用authlogic + facebook实现相同的功能,而不是像railscast中所示的设计+ twitter.
也许我的理解has_many
还是不够好,但在railscasts瑞安有下面的代码中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
Run Code Online (Sandbox Code Playgroud)
在我的实现中current_user.authentications
返回一个数组[]
如何调用find_or_create_by_provider_and_uid
数组?
我的实施错了吗?不是has_many
假设返回一个数组?
我得到的错误是我正在调用find_or_create_by_provider_and_uid
一个nil
对象.
current_user.authentications
没有用,因为用户还没有任何身份验证.
小智 5
该数组实际上是一个AssociationProxy
实例,它将所有方法调用委托给内部对象,在has_many
关联的情况下这是一个数组(也见这个问题).这意味着你应该可以find_or_create_by_provider_and_uid
在它上面调用魔术方法,如范围等等.
我发现了这个问题,因为我偶然发现了类似的问题:由于某种原因,我无法打电话ActiveRecord::Relation#klass
找出模型类:
post.comments.klass # => NoMethodError
Run Code Online (Sandbox Code Playgroud)
但是通过relation
先调用你可以获得一个正常的ActiveRecord::Relation
实例:
post.comments.relation.klass # => Comment
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2467 次 |
最近记录: |