【问题标题】:has_one :through and has_many :throughhas_one :through 和 has_many :through
【发布时间】:2014-05-03 19:38:04
【问题描述】:
rails -v = 4.0
ruby -v = 2.1.1

has_one :through 有一些严重的问题。所有 google 1st 2 pages 链接都是蓝色的(我已经浏览了所有这些)。

我的问题是当我尝试做时

post = Post.last
post.build_user

它说未定义的方法`build_user'。我的关联类如下。

class Post < ActiveRecord::Base    
    has_one :user_post
    has_one :user, class_name: "User", through: :user_post

   accepts_nested_attributes_for :user
end

class UserPost < ActiveRecord::Base
    belongs_to :user
    belongs_to :post
end

class User < ActiveRecord::Base
    has_many :user_posts
    has_many :posts, through: :user_posts 
end

如果有人请帮忙解决这个问题,那就太好了。

非常感谢。

【问题讨论】:

    标签: ruby ruby-on-rails-4 ruby-on-rails-3.2 ruby-on-rails-3.1


    【解决方案1】:

    您正在尝试在PostUser 之间设置Many-to-Many Relationship,但您当前的设置不正确。

    您需要在Post 模型中使用has_many 而不是has_one

    class Post < ActiveRecord::Base    
      has_many :user_posts
      has_many :users, through: :user_posts
    end
    

    在此之后,您可以将用户构建为:

    post = Post.last
    post.users.build
    

    更新

    您收到错误为undefined methodbuild_user'.because you can only usepost.build_userif association betweenPostandUserishas_one`,定义如下:

    class Post < ActiveRecord::Base
      has_one :user
    end
    class User < ActiveRecord::Base
      belongs_to :post    # foreign key - post_id
    end
    

    更新 2

    另外,逻辑上A user has_many posts AND A post has one User 所以你的设置应该是理想的

    class Post < ActiveRecord::Base
      belongs_to :user   # foreign key - user_id
    end
    class User < ActiveRecord::Base
      has_many :posts    
    end
    

    在此之后,您可以为用户构建帖子:

    user = User.last
    user.posts.build
    

    为帖子建立用户:

    post = Post.last
    post.build_user
    

    【讨论】:

    • 一篇帖子怎么可能有多个用户?
    • 在答案中阅读我的更新部分
    • 棘手的问题
    • 也阅读我的 UPDATE2。
    • :),理想情况下是正确的,但他想将预制帖子与用户相关联。不是吗?
    猜你喜欢
    • 2019-03-04
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多