关于设置具有多种关系的 Rails 模型的建议 (belongs_to)

发布于 2024-11-23 23:16:55 字数 1209 浏览 0 评论 0原文

在继续之前,即将做出设计决策并寻求有关“Rails 方式”的一些验证或建议。

摘要:

  • 用户创建帖子
  • 帖子可以包含(一个或多个)照片
  • 帖子可以(可选)与事件相关反过来,
  • 帖子中的照片也与所述事件相关

,其中一个要求是轻松显示给定事件的所有照片。另一种方法是显示给定用户提交的所有照片。

我最初假设:

class Photo < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
  belongs_to :event
...
end

但是我在构建 Post 控制器中的所有关系时遇到了麻烦:

class PostsController < ApplicationController
  before_filter :login_required, :except => [:index, :show]

  def create
    @user = User.find(session[:user_id])
    @post = @user.posts.create(params[:post])
    # how/where to assign Event?
    ...
  end
  ...
end

我可以循环并构建 Post 模型中的每个 :photo 参数...但不确定如何/在哪里分配 event_id?这让我想知道是否有更好的方法?

也许我应该探索 has_many :through 关系,其中:

User has_many :photos, :through => :posts

事件 has_many :photos, :through => :posts

简而言之,我应该存储 user_id & 吗?每张照片中的 event_id 以便更轻松地根据需要获取它们?如果是这样,如何最好地分配关联?或者,这会变得难以维护并因此普遍不受欢迎,我应该使用 has_many :through 方法吗?

About to make a design decision and looking for a little validation or advice on the "Rails way" before proceeding.

Summary:

  • Users create Posts
  • Posts can include (one or more) Photos
  • Posts can be (optionally) related to an Event
  • In turn Photos from a Post are also related to said Event

One requirement, among others, would be to easily display all Photos from a given Event. Another would be showing all Photos submitted by a given User.

I originally assumed:

class Photo < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
  belongs_to :event
...
end

But I'm having trouble building all the relationships in the Post controller:

class PostsController < ApplicationController
  before_filter :login_required, :except => [:index, :show]

  def create
    @user = User.find(session[:user_id])
    @post = @user.posts.create(params[:post])
    # how/where to assign Event?
    ...
  end
  ...
end

I can loop through and build each :photo param in the Post model...but not sure how/where to assign the event_id? Which makes me wonder if maybe there's a better approach?

Perhaps I should be exploring has_many :through relationships where:

User has_many :photos, :through => :posts

Event has_many :photos, :through => :posts

In a nutshell, should I be storing the user_id & event_id in every Photo to make it easier to grab them as needed? If so, how best to assign the associations? Or, will this become hard to maintain and thus generally frowned upon and I should use a has_many :through approach?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文