【问题标题】:How to take a hash of key/val pairs and set ActiveRecord attributes with it如何获取 key/val 对的哈希并使用它设置 ActiveRecord 属性
【发布时间】:2013-12-26 02:22:05
【问题描述】:

我有一个通过远程 Web API 检索的 Ruby 哈希。我有一个 ActiveRecord 模型,它与散列中的键具有相同的属性。 Ruby on Rails 4 是否有一种简单的方法将键/值对从散列分配给模型实例?是否可以忽略不存在的键?

【问题讨论】:

    标签: ruby activerecord ruby-on-rails-4


    【解决方案1】:

    超级简单!

    更新属性而不保存:

    model.attributes = your_hash
    # in spite of resembling an assignemnt, it just sets the given attributes
    

    更新属性保存:

    model.update_attributes(your_hash)
    # if it fails because of validation, the attributes are update in your object
    # but not in the database
    

    更新属性,保存,如果无法保存则提升

    model.update_attributes!(your_hash)
    

    【讨论】:

      【解决方案2】:

      根据Rails docs

      更新(属性)

      根据传入的哈希更新模型的属性并保存记录,所有这些都包含在事务中。如果对象无效,则保存失败,返回false。

      所以试试

      model.update(dat_hash) #dat_hash being the hash with the attributes

      我在 Rails 3.2 中使用 update_attributes 做同样的事情,这是同样的事情。这是我的代码:

      def update
        @form = get_form(params[:id])
        @form.update_attributes(params[:form])
        @form.save
        if @form.save
          render json: @form
        else
          render json: @form.errors.full_messages, status: :unprocessable_entity
        end
      end
      

      它只更新哈希中的属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-09
        • 1970-01-01
        相关资源
        最近更新 更多