【问题标题】:This relationship doesn't allow for me to create posts through a user object这种关系不允许我通过用户对象创建帖子
【发布时间】:2014-04-27 18:02:43
【问题描述】:

我需要帮助在 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

问题?

rails c 中的以下内容有效 - 用户 ID 未传入:

User.find_by_x(x).blogs.find_by_x(x).post.create(x)

帖子是为已附加博客的用户创建的,但由于这种链接的工作方式,只有blog_id 被传递给帖子,而不是user_id 至关重要的是我同时拥有博客和用户ID。

所以我想,为什么不直接通过用户对象创建帖子并传入博客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.

我认为问题在于我有一个连接表,我说的是has_many :posts, through: blogs 大多数人可能会认为“只需删除直通部分”。我如何需要这种类型的关系,其中一个用户可以拥有许多博客,博客可以属于许多用户,帖子属于一个博客和一个用户,但一个用户可以有很多帖子....

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

【问题讨论】:

    标签: ruby-on-rails model relationship


    【解决方案1】:

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

    这是通常的做法:

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

    【讨论】:

    • 考虑到我还没有创建控制器,所以没有 current_user 但有趣的答案
    【解决方案2】:

    这个问题的正确解决方案是几件事,我需要确保博客和用户之间的关系与用户和博客相同,所以在我添加的博客模型中:

    has_and_belongs_to_many :users, join_table: 'blogs_users'

    然后我需要在帖子级别而不是用户级别创建帖子。所以,@user.posts.create() 我需要做 Post.create(blog_id: x, user_id: x) 然后 @user.posts 将正常工作(假设用户有 2 个博客,每个博客都有一篇文章,您将获得两篇文章)

    【讨论】:

      猜你喜欢
      • 2020-03-06
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多