繁体   English   中英

Rails ActiveRecord has_many通过不起作用

[英]Rails ActiveRecord has_many through not working

我有一个Rails应用,其中用户有孩子。 所以我有两个模型::users和:children。

我曾经有一对多的关系(has_many / belongs_to),但是我想将其开放为多对多的关系,在其中可以存储有关该关系的变量。 因此,我将关系更改为“ has_many through”关系。 我创建了一个名为:relationships的表。 一个小警告:我希望用户的Foreign_key是:parent_id。 这是我设置它们的方式:

架构:

create_table "relationships", :force => true do |t|
    t.integer  "child_id"
    t.integer  "parent_id"
    t.datetime "created_at"
.
.
.

create_table "users", :force => true do |t|
    t.string   "email",                                  :null => false
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
    t.string   "first_name"
    t.string   "last_name"
.
.
.

create_table "children", :force => true do |t|
    t.string   "name",                :null => false
    t.integer  "parent_id",           :null => false
    t.datetime "created_at",          :null => false
.
.
.

类定义:

user.rb:

has_many :relationships, foreign_key: "parent_id"
has_many :children, :through => :relationships, foreign_key: "parent_id"

child.rb:

has_many :relationships, foreign_key: "child_id"
has_many :parents, :through => :relationships

Relationship.rb:

belongs_to :parent, class_name: "User", :foreign_key => :parent_id
belongs_to :child, class_name: "Child", :foreign_key => :child_id

现在,当我选择一个特定的用户并尝试获取user.children时,我得到[]作为响应。 如果我尝试添加新的孩子,那么它也不起作用。 我可以定义父级和子级,但是当它尝试保存时,无法将两者关联。 它没有看到父母,所以我得到了错误:

* ActiveRecord :: StatementInvalid(PG :: Error:错误:列“ parent_id”中的空值违反了非空约束*

如果我将类定义切换回一对多设置,则可以很好地访问子级。 我不明白问题是什么。 任何帮助将不胜感激。

谢谢

您如何建立关系? 在创建如下关系时, @user.children通过给定的示例为我工作:

@user.relationships.build(child_id: ...) 

如果要创建子级作为嵌套属性,则应允许在子级表中将parent_id设为null。

更改

create_table "children", :force => true do |t|
  t.string   "name",                :null => false
  t.integer  "parent_id",           :null => false
  t.datetime "created_at",          :null => false
end

   create_table "children", :force => true do |t|
      t.string   "name",                :null => false
      t.integer  "parent_id"
      t.datetime "created_at",          :null => false
    end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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