【发布时间】:2014-01-20 06:13:02
【问题描述】:
目前,我使用 has_and_belongs_to_many 关联在我的应用中定义了两个模型,Accounts 和 Users。
应用内的帐户是指公司等组织。
我能够轻松获取当前用户,但如果当前用户有多个帐户,我正在努力寻找一种方法来构建一个对象来存储当前帐户。
现在我默认使用属于当前用户的第一个帐户,我猜测解决方案将是在我定义的路由中包含所选帐户 id 参数,但我不是真的很确定该怎么做,因为我对 RoR 还很陌生,如果可能的话,我更愿意在幕后设置它,而不在 URL 中显示帐户 ID。
编辑 - 添加代码
models/account.rb
class Account < ActiveRecord::Base
#define relationship to users
has_and_belongs_to_many :users
#...
end
models/user.rb
class User < ActiveRecord::Base
#define relationship to account
has_and_belongs_to_many :accounts
#...
end
** 在将帐户和用户关联更新到 habtm 之前之前的“current_account”实施。
控制器/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_account
private
def current_account
if user_signed_in?
@current_account ||= Account.find(current_user.account_id)
end
end
end
上面的 current_account 帮助器方法不再有效,因为我已经将我的关联从 Account has many Users 和 Users belongs to Account 更改为 Accounts has and属于 many Users,反之亦然。现在我已经将上面的代码更新为
@current_account ||= current_user.accounts[0]
但显然它仍然是一个静态变量,我需要它是动态的,具体取决于用户选择的帐户。
我也在使用 devise,所以我可以利用他们的 current_user 辅助方法轻松获取当前用户。
任何帮助将不胜感激!
【问题讨论】:
-
您能否提供一些示例代码来说明您要做什么?列出所有连接到关系的模型。一开始,Habtm 关系似乎是灵丹妙药,但结果往往是有一个更简单的答案。
-
@Saifis - 更新了我迄今为止实施的问题。
标签: ruby-on-rails ruby-on-rails-3 has-and-belongs-to-many