2017-06-08 64 views
0

新的rails。我创建了一个包含多个数据库表的项目,它们之间相互关联。我想知道如何在创建实例后添加外键引用。下面的代码:Ruby on Rails:多对多实例

在架构:

class Blog < ActiveRecord::Base 
     has_many :posts 
     has_many :owners 
     has_many :users, through: :owners 
    end 

    class Owner < ActiveRecord::Base 
     belongs_to :user 
     belongs_to :blog 
    end 

    class User < ActiveRecord::Base 
     has_many :messages 
     has_many :posts 
     has_many :owners 
     has_many :blogs, through: :owners 
    end 

型号:

class User < ActiveRecord::Base 
    has_many :messages 
    has_many :posts 
    has_many :owners 
    has_many :blogs, through: :owners 
end 

class Owner < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :blog 
end 

class Blog < ActiveRecord::Base 
    has_many :posts 
    has_many :owners 
    has_many :users, through: :owners 
end 

在轨控制台:

blog1 = Blog.first 
user1 = User.first 
blog1.users = user1 
NoMethodError: undefined method `each' for #<User:0x0000000487e9f8> 

回答

0

由于博客has many用户,.users将是一个集合(数组或ActiveRecord_Relation)。

尝试:blog1.users << user1

<< (shovel operator) docs

1

如果你试图让这个USER1成为博客的主人,你可以尝试

blog1 = Blog.first 
user1 = User.first 
Owner.create(user: user1, blog: blog1) 

Owner.create(user: User.first, blog:Blog.first) 

希望我回答你的问题!

0

当你正在写blog1.users,你回来一个数组,所以做= something将无法​​正常工作。虽然您可以使用<<array.push()添加到阵列,但这不是最佳做法。

相反,has_many(或has_one等)允许您使用build_表示法来创建相关对象。所以你可以这样做:blog1.users.build,它会创建一个博客引用的新用户。或者如果你想坚持下去,你可以拨打.users.create

有很多方法可以解决它,但如果可用的话使用ActiveRecord方法是保持代码可读性和简短性的好方法。