首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby on Rails:多对多实例

问Ruby on Rails:多对多实例
EN

Stack Overflow用户
提问于 2017-06-09 03:37:00
回答 0查看 53关注 0票数 0

rails新手。我正在创建一个具有多个数据库表的项目,这些表都是相互关联的。我想知道如何在实例创建后将外键引用添加到实例。代码如下:

在架构中:

代码语言:javascript
复制
    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

型号:

代码语言:javascript
复制
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

在rails控制台中:

代码语言:javascript
复制
blog1 = Blog.first
user1 = User.first
blog1.users = user1
NoMethodError: undefined method `each' for #<User:0x0000000487e9f8>
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44444224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档