has_one:through和has_many:through

时间:2014-05-03 19:38:04

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

rails -v = 4.0
ruby -v = 2.1.1

我对has_one有严重问题:通过。所有谷歌前2页链接都是蓝色的(我已经完成了所有这些)。

我的问题是当我尝试

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

如果有人帮忙解决这个问题,那真的很棒。

很有责任。

1 个答案:

答案 0 :(得分:1)

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

您需要在has_many模型中使用has_one代替Post

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

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

post = Post.last
post.users.build

<强>更新

您收到的错误为undefined method build_user'。because you can only use post.build_user if association between发布and用户is has_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