I want to set up a relationship other than table+_id in rails.

Asked 2 years ago, Updated 2 years ago, 58 views

Item_id in parent table, item_id in child table, item_id as key

Parent table has_many child table
Child Table Belongs_to Parent Table

I want to have a one-to-many relationship like this

ruby-on-rails rails-activerecord

2022-09-29 21:51

1 Answers

Parent table, Child table.
The parent item_id is interpreted as the model id or something unrelated to the parent-child relationship, and interpreted as asking for a solution if the ID name-class association is outside the rails rule.

$railsg model Parent item_id: integer
$ railsg model Child item_id — integer
$ rails db:migrate

After making both Parent and Child models, I think it would be good to make the following relationships.

app/models/parent.rb

class Parent <ApplicationRecord
  has_many:children,class_name:"Child",foreign_key::item_id
end

app/models/child.rb

class Child<ApplicationRecord
  belongs_to:item, class_name: "Parent"
end

This is what railsc looks like.

>Parent.create()
>5.times {Child.create(item_id:1)}
>Parent.first.children
>Child.all.map {|c|c.item}

I don't need the class_name of Has_many on the parent side because it can be associated with Child from the name Children, but even in Has_many, defining the class_name can solve the problem...


2022-09-29 21:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.