gpt4 book ai didi

ruby-on-rails - 创建具有两个 belongs_to 关联的模型的最佳实践?

转载 作者:数据小太阳 更新时间:2023-10-29 08:34:11 25 4
gpt4 key购买 nike

这是我经常遇到的一致性问题。

让我们考虑一个典型的论坛:

  • 用户可以创建帖子
  • 帖子属于一个主题
  • 帖子也属于创建它们的用户

在这两个选项之间进行选择的最佳做法是什么:

# Initialize @post on the User
def create
@post = current_user.posts.build(params[:post])
@post.topic_id = @topic.id
if @post.save
...
end
end

或者

# Initialize @post on the Topic
def create
@post = @topic.posts.build(params[:post])
@post.user_id = current_user.id
if @post.save
...
end
end

或者有没有更好的方法,考虑到在上面的示例中,@post 的 user_idtopic_id 必须添加到 attr_accessible(感觉很hacky)?

最佳答案

我设法找到的最干净的方法是使用 CanCan:当有规则 can :create, Post, :user_id => user.id 并在你的代码中添加 load_resource Controller 它将设置属性。

但并不总是合适的。如果有一些通用的解决方案来一次性初始化嵌套对象,那就太好了。

更新。我想到了另一个选择:

@post = @topic.posts.where(user_id: current_user.id).build(params[:post])

一般来说,所有这些方法都打破了 Law of Demeter .最好封装在模型的方法中,像这样:

class Topic < ActiveRecord::Base
def new_post(params={}, author=nil)
posts.build(params).tap {|p| p.user = author}
end
end

然后在 Controller 中:

@post = @topic.new_post(params[:post], current_user)

关于ruby-on-rails - 创建具有两个 belongs_to 关联的模型的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6834028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com