导轨 HABTM 连接和不便

发布于 2024-08-22 18:12:17 字数 891 浏览 5 评论 0原文

我在模型

Posts 和 Users 之间有一个有效的 HABTM 关联... posts_users 表如广告所示,并且在其 model.rb 中都有必要的 has_and_belongs_to_many

如果我使用 User.find(1).posts 它将找到所有具有有效用户名的帖子

我的问题是如何处理这种情况。

我想使用

user.posts.find(1234) 或真正从控制器中使用 eq:

current_user.posts.find(params[:id])

来保护自己免受其他用户的影响。然而这种用法会产生一些奇怪的结果。它确实有效,但 id 不是特定帖子或所有帖子的有效 id,而是返回 1 的 id,而不是 1234 的真实 ID。因此,进一步的连接例如:

user.posts.find(1234).comments

不起作用或是无效的。

为了更好地衡量,我尝试将所有放在几个地方,因为这有时可以解决过去的其他尴尬情况。仍然有一些陌生人的遭遇。

user.posts.all.first 可以工作并返回正确的 ID!,但是使用 first 并没有多大帮助。 user.posts.all.find(6933) 返回 #

还尝试了与 (:post_id => 1234 的各种组合) 返回的 id 始终为 1。

有什么想法吗?

I have a working HABTM association between the models

Posts and Users... the posts_users table is as advertised and both have the necessary has_and_belongs_to_many in their model.rb

And if I use User.find(1).posts it will find all the posts with the valid username

My question is how to deal with this situation.

I want to use

user.posts.find(1234) or really from the controller the eq:

current_user.posts.find(params[:id])

To protect myself from other users jumping around. However this usage has some strange results. It does work, but instead of the id being a valid id for a particular post or all the posts, it returns the id of 1 instead of say, the real one of 1234. So further joins such as:

user.posts.find(1234).comments

don't work or are invalid.

I tried throwing in all a few places for good measure, as that has sometimes worked for other awkward situations in the past. With a few stranger encounters still.

user.posts.all.first works and returns the correct ID!, but using first isn't really helpful. user.posts.all.find(6933) returns #<Enumerable::Enumerator:0x105343630>

Also tried various combination with (:post_id => 1234) returning an id of always 1.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

汹涌人海 2024-08-29 18:12:17

这很可能是因为您的联接表 posts_users 有一个 id 列。在您的迁移中,您的连接表应如下所示:

create_table :posts_users, :id => false do |t|
  t.references :posts
  t.references :users
end

This is most likely because your join table posts_users has an id column. In your migration your join table should look like this:

create_table :posts_users, :id => false do |t|
  t.references :posts
  t.references :users
end
陈甜 2024-08-29 18:12:17

用户通过帖子发表了很多评论怎么样?然后像 user.comments.find(:all, :conditions => { :post_id => 1234 }

How about user has many comments through posts. Then something like user.comments.find(:all, :conditions => { :post_id => 1234 }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文