【问题标题】:Check that record doesn't exist/retrieve existing record active record检查记录不存在/检索现有记录活动记录
【发布时间】:2015-12-30 02:02:30
【问题描述】:

这个问题有两个部分:

考虑具有Student - name:string, favorite_class:referencesFavoriteClass name:string, abbrev:string 的活动记录关系。

第一个问题:创建student 记录并添加favorite class(名称和缩写)时,我想检查该名称/缩写组合是否存在以及它是否为该关联加载了该组合,否则创建一个新的一个。

第二:当我尝试更新(放置)student 时,我希望能够通过favorite classabbrev 并按该部分查找记录(假设缩写是唯一的)并使用它,否则失败。

我没有看到执行此类操作的 rails 方式。

【问题讨论】:

    标签: ruby-on-rails rest activerecord rails-postgresql


    【解决方案1】:

    对于第一个问题,诀窍是使用find_or_create方法:

    #in the place where you create a new Student
    #this method return first entity from db, if it doesn't found, will create one
    fav_class = FavoriteClass.find_or_create(name: some_name, abbrev: some_abbrev)
    Student.create(name: some_student_name, favorite_class: fav_class)
    

    您可以为第二个问题做类似的事情。请给我更多的细节。

    更新 1

    如果你想更新学生最喜欢的课程,你可以这样做:

    #I assume that you use latest vertion of rails of not, use .first instead of .take
    new_class = FavoriteClass.where(abbrev: some_abbrev).take
    student.update_attributes(favorite_class: new_class) if new_class
    

    【讨论】:

    • 例如,我需要发出一个接受缩写的 put 请求,并根据该缩写加载课程并更新学生记录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 2021-12-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多