gpt4 book ai didi

mysql - 带有 ActiveRecord 的 Rails 虚拟属性

转载 作者:行者123 更新时间:2023-11-29 02:22:25 24 4
gpt4 key购买 nike

我有一个具有以下简化模式的 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

Controller 使用标准的 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 属性的表单的 View 。

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

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

{"utf8"=>"✓", "authenticity_token"=>"some_long_token", "sensor"=>{"hex"=>"E000124EB63E0001"}, "commit"=>"创建传感器"

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

最佳答案

请在允许的参数中添加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

希望对你有帮助

关于mysql - 带有 ActiveRecord 的 Rails 虚拟属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29586854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com