【问题标题】:Rails virtual attribute with ActiveRecord带有 ActiveRecord 的 Rails 虚拟属性
【发布时间】:2015-04-12 06:54:54
【问题描述】:

我有一个具有以下简化架构的 MySQL 数据库表:

create_table "sensors", force: :cascade do |t|
  t.integer  "hex_id",     limit: 8, null: false
end

其中hex_id 在MySQL 中被声明为BIGINT。我想让用户输入一个十六进制值,然后将其转换为基数 10 并将其保存在hex_id 中。为此,我想我会创建一个名为hex 的虚拟属性来存储十六进制字符串。我的Sensor 模型如下所示:

class Sensor < ActiveRecord::Base  
  attr_accessor :hex

  validates :hex, presence: true

  before_create :hex_to_bigint
  before_update :hex_to_bigint

  private
  def hex_to_bigint
    self.hex_id = hex.to_s(10)
  end
end

并且控制器正在使用标准 rails 生成的代码:

  def new
    @sensor = Sensor.new
  end

  # POST /sensors
  def create
    @sensor = Sensor.new(sensor_params)

    if @sensor.save
      redirect_to @sensor, notice: 'Sensor was successfully created.'
    else
      render :new
    end
  end

我用一个使用hex 属性的表单创建了一个视图。

<%= f.label :hex do %>HEX ID:
    <%= f.text_field :hex, required: true, pattern: '^[a-fA-F\d]+$' %>
<% end %>

当我点击提交时,params 数组有以下内容:

{"utf8"=&gt;"✓", "authenticity_token"=&gt;"some_long_token", "sensor"=&gt;{"hex"=&gt;"E000124EB63E0001"}, "commit"=&gt;"Create Sensor"}

我的问题是hex属性总是空的,我的验证失败了。网上有很多资源解释了如何使用虚拟属性,但很少有资源解释如何将它们与ActiveRecord 结合使用。我花了几个小时寻找一种方法来解决这个相当简单的问题,但没有找到任何可行的方法。任何帮助表示赞赏。我的红宝石版本是 2.0.0p481。谢谢!

【问题讨论】:

  • 请发布您在点击保存或更新后获得的控制器代码和参数
  • 您在 2 个回调中编写了 :hex_to_bigint 方法,即。创建和更新。您可以在 1 个回调中执行此操作,也只需编写以下代码 before_save :hex_to_bigint 然后它对两者都有效。
  • 感谢顶,@AmitSharma,我已将 Sensor 模型更改为使用 before_save。我还按要求添加了控制器代码和params 的内容。
  • 您是否在允许的参数中添加了hex
  • 请同时发布许可参数方法

标签: mysql ruby-on-rails-4 activerecord virtual-attribute


【解决方案1】:

请在允许的参数中添加hex。看下面的代码

private

# Never trust parameters from the scary internet, only allow the white list through.
def sensor_params
  params.require(:sensor).permit(:hex_id, :hex)
end

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多