Ruby on rails 这种关系不存在';我不允许通过用户对象创建帖子

Ruby on rails 这种关系不存在';我不允许通过用户对象创建帖子,ruby-on-rails,model,relationship,Ruby On Rails,Model,Relationship,我需要帮助修复Rails 4.1中的这种关系 用户模型关系 has_and_belongs_to_many :blogs, join_table: 'blogs_users' has_many :posts, through: :blogs has_many :posts belongs_to :blog belongs_to :user 博客模型关系 has_and_belongs_to_many :blogs, join_table: 'blogs_users' has_many :p

我需要帮助修复Rails 4.1中的这种关系

用户模型关系

has_and_belongs_to_many :blogs, join_table: 'blogs_users'
has_many :posts, through: :blogs
has_many :posts
belongs_to :blog
belongs_to :user
博客模型关系

has_and_belongs_to_many :blogs, join_table: 'blogs_users'
has_many :posts, through: :blogs
has_many :posts
belongs_to :blog
belongs_to :user
模型后关系

has_and_belongs_to_many :blogs, join_table: 'blogs_users'
has_many :posts, through: :blogs
has_many :posts
belongs_to :blog
belongs_to :user
问题

rails c
中,以下各项起作用-无论用户id是否传入:

User.find_by_x(x).blogs.find_by_x(x).post.create(x)
这篇文章是为说博客已附加的用户创建的,但由于这种链接的工作方式,只有
blog\u id
被传递到文章,而不是
user\u id
这一点至关重要,我同时拥有blog和user id

所以我想,为什么不通过user对象创建post并传入blog id呢

User.find_by_x(x).posts.create(x, blog_id: y) # Where y represents a blog the user is associated with.
好吧,这一切都很好,我接受这个错误:

ActiveRecord::HasManyThroughNestedAssociationsAreReadonly: Cannot modify association 'User#posts' because it goes through more than one other association.
我认为问题在于我有一个连接表,我是说
有很多:posts,through:blogs
大多数人可能会认为“只需删除through部分”我多么需要这种关系,一个用户可以有许多博客,博客可以属于许多用户,帖子属于一个博客和一个用户,但是一个用户可以有许多帖子


那么,有没有办法解决这个问题,以保持我的概念或

您创建帖子的方式没有多大意义

这是通常的做法:

blog = current_user.blogs.find(params[:blog_id])
post = blog.posts.create(params[:post])

respond_with(post)

解决这个问题的正确方法有两点,我需要确保博客和用户之间的关系与用户和博客之间的关系相同,因此在博客模型中我添加了:

拥有且属于多个用户:用户,加入表格:“博客用户”

然后我需要在帖子级别创建帖子,而不是用户级别。因此,我需要做的不是,
@user.posts.create()
而是
Post.create(blog\u id:x,user\u id:x)
然后是@user.posts
将正常工作(假设用户有两个博客,每个博客中有一篇文章,您将返回两篇文章)

考虑到我还没有创建控制器,没有
当前用户
,但答案很有趣