Create 2 references to the same model in another Rails: 4

0

I have 2 models, one for users and another for articles

Users:
    id
    name
    email
    password
    role

Articles:
    id
    title
    body

I want my article to have 2 references to my user table, one for the user who created the article and another for the user (role: administrator) who approved it, but I do not know how to do it without making a many-to-many relationship. it seems a lot for this case that I just need a record related to 2 users

in the end, Articles should look like this

Articles:

id
title
body
user_id < == (admin / moderator role) - Both of     User model
user_id < == (user role)

I have already established the roles with CAN CAN, I just do not know how to make this type of relationship.

Articles do not have more relationships with any other user than the one who created it and the one who approved it.

    
asked by J.leo 04.09.2017 в 02:07
source

1 answer

2

You can make the Articles relationship such as the samples, only you must use different key names; for example:

class User < ApplicationRecord
  has_many :articles
end

class Article < ApplicationRecord
  belongs_to :user
  belongs_to :admin, class_name: "User"
end

Here class_name: "User" is the one that causes admin to point to table users , but takes the key admin_id instead of user_id due to the default values of Rails (ie take the name of the relationship and add _id ).

In the CreateArticles migration, you must include the two columns:

class CreateArticles < ActiveRecord::Migration[5.1]
  def change
    create_table :articles do |t|
      # ...
      t.integer :user_id
      t.integer :admin_id
    end
  end
end

With this relationship you can obtain the user or administrator of a specific article using user or admin respectively; for example, for the article with id == 1 :

Article.find(1).user
Article.find(1).admin
    
answered by 04.09.2017 в 02:34