gpt4 book ai didi

ruby-on-rails - 努力理解模型和关联是如何保存在 Rails 中的

转载 作者:数据小太阳 更新时间:2023-10-29 07:17:53 26 4
gpt4 key购买 nike

我是 ruby​​ 和 rails 的新手,我想尽可能地遵循编码标准和约定,所以我不会养成任何坏习惯。我有两个模型:Course 和 Location。一门类(class)属于一个位置,因为一门类(class)只能有一个位置。一个位置有_许多类(class),因为一个位置可以由多个类(class)共享。

创建类(class)时,位置可能已经存在,可以通过其 ID 找到。或者该位置可能尚不存在,在这种情况下必须创建新的位置记录。我的类(class) Controller 具有以下创建操作。

def create
@course = Course.new(params[:course])

if params[:course][:location][:id].blank?
@course.location = Location.create(params[:course][:location])
else
@course.location = Location.find_by_id(params[:course][:location][:id])
end

@course.save

respond_with @course
end

请注意,这是一个仅以 JSON 响应的 REST API。发出请求的 javascript 发布一个 JSON 数组,其格式与 GET 请求返回的格式相同

{
"course":
{
"title":"US History",
"credits":"3",
"max_students":"100",
"location":
{
"id":"",
"building":"Freedom Hall",
"room":"301"
}
}
}

or

{
"course":
{
"title":"US History",
"credits":"3",
"max_students":"100",
"location":
{
"id":"12", # this is the only difference
"building":"Freedom Hall",
"room":"301"
}
}
}
  1. 与我读过的所有示例相比,这段代码看起来并不那么优雅。有更好的分解方法吗?
  2. 如果 Location.create 引发异常,@course.save 是否仍会被调用?我需要使用 Location.create! 吗?
  3. 同样,验证错误是否会在@course.errors 中结束,即使错误发生在 Location 模型中?我是否需要从异常中解救出来,以便将错误返回给客户?

非常感谢您提供的所有帮助!

最佳答案

您可以使用 find_or_initialize_by_id 清理它。这应该有效:

def create
@course = Course.new(params[:course])
@course.location = Location.find_or_initialize_by_id(params[:course][:location][:id],
params[:course][:location])
@course.save
respond_with @course
end

关于你的第二个问题,如果 Location.create(或 Location.find) 引发异常(因为它们会先发生)。然而,按照我上面的编码方式,异常会在代码中的同一点发生,当 save 被调用时,关联也会被保存。

关于ruby-on-rails - 努力理解模型和关联是如何保存在 Rails 中的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13082267/

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