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 次 |
| 最近记录: |