【发布时间】:2015-06-09 09:32:56
【问题描述】:
我有
class User::AuthInfo < ActiveRecord::Base
self.table_name = "auth_infos"
belongs_to :authenticable, polymorphic: true
end
和
class User::Customer < ActiveRecord::Base
self.table_name = "customers"
has_one :auth_info, as: :authenticable
end
我希望这样做:
User::Customer.last.auth_info
输出应该是来自auth_info 的记录。但我看到查询是错误的:
SELECT `auth_infos`.* FROM `auth_infos` WHERE `auth_infos`.`customer_id` = 8 LIMIT 1
我的表有 authenticable_id 和 authenticable_type, 文档告诉我创建以使多态工作的字段。
怎么了?为什么使用customer_id 而不是authenticable_id?
编辑:
这里是两张表的架构:
编辑:
我确实省略了一件事,因为我认为这并不重要,但它似乎会导致问题,在我使用的 Customer 模型上,我使用了一个关注点:
include User::Loggable
以下是关注的内容:
module User::Loggable
extend ActiveSupport::Concern
included do
has_one :auth_info
end
def login ip_address
@session_ip = ip_address
create_session_token
self.save
end
def renew_session
@session_token_expire = renew_session
end
def destroy_session
self.session_token = nil
self.session_token_expire = nil
self.save
end
def verify_session! (token, ip)
if (ip == session_ip && token = session_token && session_token_expire.to_i > Time.now.to_i)
true
else
false
end
end
private
def new_token( string = "" )
...
end
def digest_token token
..
end
def register_user
a = User.new email_address: self.email_address, kind: self.class.name
a.save
end
def create_session_token
@session_token = digest_token(new_token())
@session_token_expire = (Time.now + AUTHENTICATION[::Rails.env]["expiration"]["session"].hour.to_i).strftime("%Y-%m-%d %H:%M:%S")
end
def renew_session
session_token_expire = (Time.now + AUTHENTICATION[::Rails.env]["expiration"]["session"] + 3.hour).strftime("%Y-%m-%d %H:%M:%S")
end
module ClassMethods
def authenticated_account
current_account ||= self.find_by_session_token() if CbsoltCore::App::Environment.account_session_token && CbsoltCore::App::Environment.account_session_token != ""
# mettere parte API token
current_account
end
end
end
我已经在我的模块中推荐了包含问题,并且它有效。为什么?
【问题讨论】:
-
您的实际表名是什么?而不是提供自定义名称?
-
表名其实是自定义提供的!!!但我已经更改为默认设置并删除了自定义设置。所以表是“user_auth_infos”和“user_customers”。但注意到变化。
-
'user_auth_infos'中有authenticable_type和authenticable_id吗?您可以编辑您的问题并根据模型向我显示字段吗?
-
@ChitrankSamaiya 做到了。看一看!谢谢
-
嗨 Ciaben,这是因为它可能会覆盖您的关注并使用关注关联。
标签: ruby ruby-on-rails-4 associations polymorphic-associations