Access attributes from associated model in model

无人久伴 提交于 2020-01-07 07:37:09

问题


I'm trying to apply a rule to an ability class

Each user in my application (except admins, but we'll ignore that) belongs_to a practice, defined in another model.

The practice may want to be suspended from access for one reason or another.

I want to say in my ability model

if user.practice.suspended? 
 can :read, Client, :practice_id => user.practice_id
else 
can :manage, CLient, :practice_id => user.practice_id
etc....

But for some reason, whilst I can use

user.practice_id

in the ability model I can't use

user.practice.<attribute>

Any ideas for a way around that?

models/user.rb

belongs_to :practice

models/practice.rb

A practice has many users. The only user who won't have a practice are those with role :admin

has_many :users

回答1:


I think you have the relationships backwards.

It should be that "User has_many (or has_one) practice" and "Practice belongs_to user". This would signify that the foreign_key (in this case user_id) is actually in the practice table instead of the user table.

Try this:

User.rb

has_one :practice

Practice.rb

belongs_to :user

Create a migration to add user_id to practice

add_column :practices, :user_id, :integer

Then you can call practice from user like so:

user.practice.x


来源:https://stackoverflow.com/questions/19572131/access-attributes-from-associated-model-in-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!