问题
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