[英]Models with multiple belong_to and naming
I'm creating my own little task system in Ruby on Rails, but I need some guidance on what to call my attributes, and if I'm thinking about the right solution.我正在 Ruby on Rails 中创建我自己的小任务系统,但我需要一些关于如何调用我的属性的指导,以及我是否正在考虑正确的解决方案。
So I have a Task model.所以我有一个任务模型。
A task can have two relations to a user: The creator and the user that's responsible for the task.任务可以与用户有两种关系:创建者和负责任务的用户。
I can of course just call my attributes: creator:integer , and a responsible:integer , but what is the preferred Ruby on Rails way of doing this?我当然可以只调用我的属性: creator:integer和Responsible:integer ,但是 Ruby on Rails 的首选方法是什么?
Should they just be called the above, or creator_user_id:integer or should I make a relation table with a user_id and a task_id and then a role?他们应该被称为上面的,还是creator_user_id:integer,还是我应该用user_id和task_id然后一个角色创建一个关系表?
In your migration you'll want the following:在您的迁移中,您需要以下内容:
class CreateTasks < ActiveRecord::Migration
def change
create_table :tasks do |t|
t.references :creator
t.references :responsible
t.timestamps
end
add_index :tasks, :creator_id
add_index :tasks, :responsible_id
end
end
This was generated by: rails g model task creator:references responsible:references
这是由以下生成的: rails g model task creator:references responsible:references
In your database this will create a tasks
table with two columns: creator_id
and responsible_id
.在你的数据库,这将创建一个tasks
表,两列: creator_id
和responsible_id
。 By default Ruby on Rails will think that these columns refer to two ActiveRecord models, Creator
and Responsible
.默认情况下,Ruby on Rails 会认为这些列引用两个 ActiveRecord 模型, Creator
和Responsible
。 However, as you want these to refer to your User
model you'll need to add the following to your Task
model:但是,由于您希望这些引用您的User
模型,您需要将以下内容添加到您的Task
模型中:
In app/models/tasks.rb
在app/models/tasks.rb
class Tasks < ActiveRecord::Base
belongs_to :creator, :class_name => 'User'
belongs_to :responsible, :class_name => 'User'
end
This will tell Ruby on Rails to use the User
model for these relations.这将告诉 Ruby on Rails 对这些关系使用User
模型。 So when you do something like task.creator
you'll get back a User
model, and the same for task.responsible
.因此,当您执行诸如task.creator
类的task.creator
您将返回一个User
模型,对于task.responsible
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.