如何从 2 级嵌套模型访问记录
我有 3 个模型用户、列表和消息。我想要的是经过身份验证的用户拥有许多列表。然后列表可以有多个消息。因此,消息通过列表模型与用户联系在一起。我能够获取用户列表,但无法获取他通过列表拥有的用户消息。以下是我目前拥有的协会。
class User < ActiveRecord::Base
has_many :listings, :dependent => :destroy
end
class Listing < ActiveRecord::Base
belongs_to :user
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :listing
end
要创建一条消息,我只需这样做;
@listing = Listing.find(params[:listing_id])
@message = @listing.messages.build(params[:message])
并获取用户的列表我有这个;
@user_listings = Listing.user_listings(current_user)
但事实证明,将消息与用户的列表相关联是很难的。我做错了什么或者我该如何解决这个问题?帮助表示赞赏。
I have 3 models User,Listing and Message. What I want is for an authenticated user to have many listings. The listings then can have multiple messages. So the messages are tied to the user through the listing model. I am able to get a users listings but not able to get the users messages which he owns through the listings. Here are the associations that I currently have.
class User < ActiveRecord::Base
has_many :listings, :dependent => :destroy
end
class Listing < ActiveRecord::Base
belongs_to :user
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :listing
end
To create a message I simply do this;
@listing = Listing.find(params[:listing_id])
@message = @listing.messages.build(params[:message])
And getting the user's listing i have this;
@user_listings = Listing.user_listings(current_user)
But getting the messages tied to the user's listings proves to be elusive. What am I doing wrong or how do I go about this? help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
仍然不确定 user_listings 来自哪里,但为什么不这样做:
在一个查询中包含预取所有列表的关联消息,以便它们不会在循环中获取,从而导致 n+1 查询。
如果您不需要列表数据,则可以使用另一种方法。
Still not sure where user_listings comes from but why not this:
Include prefetches all the listings' associated messages in one query in order that they're not fetched in the loop causing n+1 querying.
Or another approach, if you don't need the listings data.
关于您的评论已更新。
您可能只想将 has_many :messages 添加到用户类中,并将 user_id 列添加到 Message 中。然后你可以做
current_user.messages
updated regarding your comment.
You may want to just add has_many :messages to the user class as well and add a user_id column to Message. Then you could just do
current_user.messages
像这样的事情怎么样:
这样你就不必将消息与用户“绑定”,因为它总是通过列表关联访问:
或者我误解了你的问题?
How about something like this:
That way you dont have to "tie" the messages with the user because it is always accessed through the listing association:
Or have I misunderstood your question?
如果您已经拉取了 current_user 。您可以直接通过调用
current_user.listings
而不是
@user_listings = Listing.user_listings(current_user)来访问列表
If you have current_user pulled already. You can just access listings directly by calling
current_user.listings
instead of
@user_listings = Listing.user_listings(current_user)