简体   繁体   中英

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.

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?

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?

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

In your database this will create a tasks table with two columns: creator_id and responsible_id . By default Ruby on Rails will think that these columns refer to two ActiveRecord models, Creator and Responsible . However, as you want these to refer to your User model you'll need to add the following to your Task model:

In 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. So when you do something like task.creator you'll get back a User model, and the same for task.responsible .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM