- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我是 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"
}
}
}
非常感谢您提供的所有帮助!
最佳答案
您可以使用 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/
我正在尝试为我的项目创建一些单元测试,经过大量挖掘之后,我发现了Effort,这个想法很棒,它模拟数据库而不是处理伪造的DBContext,顺便说一句,很难做到正确使用复杂的架构。 但是,我将用户的电
我正在尝试对某些响应 Entity Framework 数据库上下文的类进行单元测试。为了寻求帮助,我设法找到了一个名为 Effort 的库,它似乎有点旧,而且没有很好的文档记录,但它似乎可以工作,而
这两天,Auto-GPT 爆火 https://github.com/Torantulino/Auto-GPT 它是一款让最强语言模型GPT-4能够自主完成任务的模型,让整个AI圈疯
为什么会出现这个异常?这是错误吗? 我正在使用 EF 测试库 Effort 创建我的数据库的内存实例并遇到这个有趣的场景: 打开DbContext1 将项目添加到表(不保存) 关闭DbContext1
我是一名优秀的程序员,十分优秀!