努力了解如何在rails中保存模型和关联

gle*_*ine 5 ruby validation json ruby-on-rails associations

我是ruby和rails的新手,我希望尽可能遵循编码标准和惯例,所以我不会养成任何坏习惯.我有两个模型:课程和位置.课程属于一个位置,因为课程只能有一个位置.一个位置has_many课程,因为一个位置可以由多个课程共享.

创建课程时,可能已存在通过其ID找到的位置.或者该位置可能尚不存在,在这种情况下,必须创建新的位置记录.我的课程控制器具有以下创建操作.

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
Run Code Online (Sandbox Code Playgroud)

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

{
  "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"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 与我读过的所有例子相比,这段代码看起来并不那么优雅.是否有更好的方法来考虑它?
  2. 如果Location.create引发异常,@ course.save仍会被调用吗?我需要使用Location.create!?
  3. 同样,即使错误发生在Location模型上,验证错误也会在@ course.errors中结束吗?我是否需要从异常中解救出来以便将错误返回给客户端?

非常感谢您的帮助!

Chr*_*erg 2

您可以使用 来清理它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
Run Code Online (Sandbox Code Playgroud)

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