开发者

insert column in with same value as primary key

开发者 https://www.devze.com 2023-04-11 09:26 出处:网络
is possible in Rails, to insert row and to assign value of id to specific column, e.g. if i have table which have ID and LINK columns where LINK is link to same table:

is possible in Rails, to insert row and to assign value of id to specific column, e.g. if i have table which have ID and LINK columns where LINK is link to same table:

ID | LINK
1  |   1
2  |   1
3  |   1

Inserting columns 2 and 3 are easy, but is there any way to insert column 1 with single INSERT st开发者_如何学运维atement?

Is this possible via rails syntax or i need custom SQL (on PostgreSQL) ?

[Of course, this can be done with INSERT/UPDATE but i need to disable updates on this table]

tx Zaharije


This is a self-joining table. You don't need to write the SQL yourself. Just define this relationship in the model like so:

class Employee < ActiveRecord::Base
  has_many :subordinates, :class_name => "Employee"
  belongs_to :manager, :class_name => "Employee",
    :foreign_key => "manager_id"  # or what you call LINK
end

Also, link probably isn't a good column name, try to pick something more descriptive if you can.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号