Write a migration with reference to a model twice
In the migration, create two different columns for each kind of user. For example:
add_column :messages, :sender_id, :integer
add_column :messages, :receiver_id, :integer
Then in the model, that's where the logic to map each column to the User class happens:
belongs_to :sender, :class_name => 'User'
belongs_to :receiver, :class_name => 'User'
Of course, use your own words for sender
and receiver
, but Rails will automatically associate sender
to the sender_id
column (and the same logic for receiver
)
You will then be able to interact with both user user.sender
and user.receiver
.
How do I add migration with multiple references to the same model in one table? Ruby/Rails
You can do this simply with the add_column
method in your migrations and set up the proper associations in your classes:
class AddFields < ActiveRecord::Migration
def change
add_column :tickets, :image_1_id, :integer
add_column :tickets, :image_2_id, :integer
end
end
class Ticket < ActiveRecord::Base
belongs_to :image_1, :class_name => "Image"
belongs_to :image_2, :class_name => "Image"
end
class Image < ActiveRecord::Base
has_many :primary_tickets, :class_name => "Ticket", :foreign_key => "image_1_id"
has_many :secondary_tickets, :class_name => "Ticket", :foreign_key => "image_2_id"
end
This blog post, Creating Multiple Associations with the Same Table, goes into more detail.
Ruby on rails - Reference the same model twice?
Add this to your Model
belongs_to :sender, :class_name => "User"
belongs_to :recipient, :class_name => "User"
And you are able to call @message.sender
and @message.recipient
and both reference to the User model.
Instead of user:references
in your generate command, you'd need sender:references
and recipient:references
Referencing the same model twice in Rails with a simple entity?
You can't actually use a single assocation here as ActiveRecord does not support assocations where the foreign key could be in one of two columns. Each has_one
/has_many
corresponds to a single foreign key column on the inverse side.
Instead you need one assocation on Address for each foreign key on Shipment:
class Shipment < ApplicationRecord
belongs_to :address_from,
class_name: 'Address',
inverse_of: :outgoing_shipments
belongs_to :address_to,
class_name: 'Address',
inverse_of: :incoming_shipments
end
class Address < ApplicationRecord
has_many :outgoing_shipments,
class_name: 'Shipment',
foreign_key: :address_from_id,
inverse_of: :address_from
has_many :incoming_shipments,
class_name: 'Shipment',
foreign_key: :address_to_id,
inverse_of: :address_to
end
While you could use has_one
here you should note that there is nothing preventing a address from having multiple shipments unless you add uniqueness constraints on shipments.address_from_id
and shipments.address_to_id
and validations. Not sure why you would want this though.
Referencing a table twice in rails/postgres
This is due to PostgreSql
not understanding how to make the custom association foreign keys.
Try changing the migration file to,
class CreateTransactions < ActiveRecord::Migration
def change
create_table :transactions do |t|
t.integer :buyer_id
t.integer :seller_id
t.integer :product_id
t.timestamps null: false
end
add_index(:transactions, :buyer_id)
add_index(:transactions, :seller_id)
add_index(:transactions, :product_id)
add_foreign_key :transactions, :users, column: :buyer_id
add_foreign_key :transactions, :users, column: :seller_id
end
end
It automatically links buyer_id
to user
, taking the power of
belongs_to :buyer, :class_name => 'User'
The above line makes the buyer_id as foreign key.
You can also try,
class CreateTransactions < ActiveRecord::Migration
def change
create_table :transactions do |t|
t.references :buyer, index: true
t.references :seller, index: true
t.references :product, index: true
t.timestamps null: false
end
add_foreign_key :transactions, :users, column: :buyer_id
add_foreign_key :transactions, :users, column: :seller_id
end
end
Creating Knex Migration Referencing the Same Table Twice
For anyone who is interested... Consolidating the working solution above using Node/ExpressJS for the server, Postgresql for the db, KnexJS/ObjectiveJS to manage Models and queries.
Here is the migration that sets up columns for buyers and sellers both of which reference the same Users table:
exports.up = function(knex, Promise) {
return knex.schema.createTable('likes', t => {
t.increments('id').primary()
t.integer('buyers_id').references('users.id').onDelete('CASCADE')
t.integer('sellers_id').references('users.id').onDelete('CASCADE')
...
t.datetime("created_at");
t.datetime("updated_at");
})
};
HEre is the Transactions Model including associations s.t. a Transaction belongs to Item Buyer(user) and Seller(user) and Item:
const BaseModel = require("./BaseModel");
// const Password = require('objection-password')();
class Transaction extends BaseModel {
static get tableName() {
return "transactions";
}
static get relationMappings () {
const User = require('./User');
const Item = require('./Item')
return {
buyer: {
relation: BaseModel.BelongsToOneRelation,
modelClass: User,
join: {
from: 'transactions.buyers_id',
to: 'users.id'
}
},
seller: {
relation: BaseModel.BelongsToOneRelation,
modelClass: User,
join: {
from: 'transactions.sellers_id',
to: 'users.id'
}
},
books: {
relation: BaseModel.BelongsToOneRelation,
modelClass: Item,
join: {
from: 'transactions.items_id',
to: 'items.id'
}
}
}
}
}
module.exports = Transaction;
Lastly, here is the express route which returns all transactions including eager loading the associated models:
let router = express.Router();
router.get('/', async (req, res) => {
const transactions = await Transaction
.query()
.eager(['buyer', 'items')
res.json(transactions);
});
rails belongs_to same model twice
Something like this:
class Task < ActiveRecord::Base
belongs_to :soldier
belongs_to :creator, class_name: Soldier, foreign_key: :created_by
end
class Soldier < ActiveRecord::Base
has_many :tasks
# Optional -- I'm unclear if you want this too?
has_many :created_tasks, class_name: Task, foreign_key: :created_by
end
The above implementation is OK. However, if you wish to stick within rails conventions (i.e. not need to manually specify a foreign_key
), then you could call the database column creator_id
instead of created_by
.
How do I create a code first model that references another model twice in C# MVC?
This error usually spawns when you are trying to rename table.
I have a suggestion for you to create your Model and try to achieve your desired results with minimal possible fields. Also, you want to use virtual
keyword only on foreign entities.
I've just tested something similar (Admin, AdminLog[Contains Admin1 and Admin2]) and it worked just fine.
Code you should try
public class System
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Jumplane
{
public int ID { get; set; }
public virtual System System1 { get; set; }
public virtual System System2 { get; set; }
}
Now that this code will work and you will be able to execute your desired LINQ query just add all other fields to it.
Some pointers (maybe subjective)
- Virtual for foreign only
- Classes start with capital letter
- No need for
SystemID
,SystemName
fields, justID
andName
will do since you will see that it belongs toSystem
Related Topics
(Ruby) How to Check Whether a Range Contains a Subset of Another Range
Why Don't Ruby Methods Have Lexical Scope
How to Get a Remote-File's Mtime Before Downloading It in Ruby
Warning: String Literal in Condition
Setting Up Env, Osx Rbenv and Bundle Battle
Activeadmin Forbiddenattributeserror
Ruby Escape Argv Argument or String as Argument to Shell Command
Ruby: Eval with String Interpolation
Refactoring Activerecord Models with a Base Class Versus a Base Module
Use Separate Authentication Model with Devise on Rails
Referencing Model with String Input
Ruby - Difference Between :Variable and @Variable
Invoke Delayed_Job Capistrano Tasks Only on Specific Servers
Ruby Time Object Converted from Float Doesn't Equal to Orignial Time Object
Rake Db:Migration Not Working on Travis-Ci Build
How to Modify the Input Type of the Rails Datetime_Select Helper