从模型中的关联模型访问属性

编程入门 行业动态 更新时间:2024-10-17 13:38:05
本文介绍了从模型中的关联模型访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将规则应用于能力类

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

models/user.rb

belongs_to :practice

models / practice.rb

models/practice.rb

实践有很多用户。 唯一没有练习的用户是那些角色:admin

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

has_many :users

推荐答案

我认为您的关系向后。

I think you have the relationships backwards.

应该是用户has_many(或has_one)练习和 Practice属于用户。这表示外键(在本例中为user_id)实际上在练习表中,而不在用户表中。

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.

尝试以下操作:

User.rb

has_one :practice

Practice.rb

Practice.rb

belongs_to :user

创建迁移以添加user_id进行练习

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

更多推荐

从模型中的关联模型访问属性

本文发布于:2023-11-17 12:28:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1610002.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!