简体   繁体   English

有没有办法将一个块传递给update_attributes?

[英]Is there a way to pass a block to update_attributes?

I'm using Rails 4.2.1. 我正在使用Rails 4.2.1。 My table has a height column. 我的桌子有一个高度栏。 Is there a way to make a height conversion on the params passed in by the user? 有没有一种方法可以对用户传递的参数进行高度转换? Something like: 就像是:

class WhateverController < ApplicationController
  def update
    current_user.update_attributes(user_params) do |u|
      u.height = convert_height_from_feet_to_inches
    end
  end

  private

    def user_params
      params.require(:user).permit(:name, :height_feet, :height_inches, :weight)
    end

    def convert_height_from_feet_to_inches
      (user_params[:height_feet] * 12) + user_params[:height_inches]
    end

end

For some reason update_attributes is not processing the block I'm trying to pass it. 由于某种原因,update_attributes没有处理我试图传递的块。 Not sure why you wouldn't be able to pass a block to update_attributes. 不知道为什么您不能将一个块传递给update_attributes。

You should do this in the model, not the controller. 您应该在模型中执行此操作,而不是在控制器中执行此操作。 Using virtual attributes you can ensure that setting either height_feet or height_inches will update height with the correct value, and vice versa: 使用虚拟属性,您可以确保设置height_feetheight_inches将更新具有正确值的height ,反之亦然:

class User < ActiveRecord::Base
  attr_reader :height_feet, :height_inches

  def height_feet=(feet)
    @height_feet = feet.present? ? feet.to_i : feet
    assign_height_from_feet_inches!
  end

  def height_inches=(inches)
    @height_inches = inches.present? ? inches.to_i : inches
    assign_height_from_feet_inches!
  end

  def height=(inches)
    self.height_feet, self.height_inches = inches.divmod(12)
  end

  private
  def assign_height_from_feet_inches!
    self[:height] =
      if self.height_feet.nil? || self.height_inches.nil?
        nil
      else
        self.height_feet * 12 + self.height_inches
      end
  end
end

Now in the controller you can just do this, and the rest will happen automatically: 现在,您可以在控制器中执行此操作,其余的操作将自动进行:

current_user.update_attributes(user_params)

This will cause the height attribute to be automatically calculated every time the record is saved. 这将导致每次保存记录时都会自动计算height属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM