gpt4 book ai didi

ruby-on-rails-3 - 虚拟属性未移至 params 内的模型哈希

转载 作者:行者123 更新时间:2023-12-04 14:49:26 25 4
gpt4 key购买 nike

我在 Rails 3.2 应用程序中遇到问题,其中通过 JSON 安静发送的虚拟属性不在 params 哈希中的正确位置。嗯,这不是我期望的地方。我的期望是否正确还有待观察。 :)

我有一个使用标准虚拟属性模式的模型,如下所示:

class Track < ActiveRecord::Base
def rating
# get logic removed for brevity
end

def rating=(value)
# set logic
end

def as_json(options={}) # so my method is in the JSON when I use respond_with/to_json
super(options.merge(methods: [:rating]))
end
end

发送到我的 Controller 的 JSON 如下所示:
{"id":1,"name":"Icarus - Main Theme 2","rating":2}

需要明确的是,name 和 id 不是虚拟的, rating 是。

在 rails 发挥它的魔力之后,我最终在 params 哈希中得到了这个:
{"id"=>"1", "name"=>"Icarus - Main Theme 2", "rating"=>2, "track"=>{"id"=>"1", "name"=>"Icarus - Main Theme 2"}}

如您所见, id 和 name 使其成为嵌套的 :track 哈希,但 rating 没有。这是预期的行为吗?它打破了在 Controller 中使用嵌套散列的(有点)标准做法,因为嵌套散列不包含我需要的所有参数。
Track.update(params[:id], params[:track]) # :track is missing rating

谢谢你的帮助!

最佳答案

我最近也遇到了这个问题。问题是,params 包装器正在查看您的模型 Track.attribute_names 以确定如何将数据映射到 :track => {params} 哈希。如果您没有关联的模型,默认将根据 Controller 名称包装参数,并包括所有值:

class SinglesController < ApplicationController
def create
#params[:single] will contain all of your attributes as it doesn't
# have an activerecord model to look at.
@track_single = Track.new(params[:single])
end
end

您可以在 Controller 中调用 wrap_parameters 来告诉操作 Controller 在包装参数时要包含哪些属性,如下所示:
class TracksController < ApplicationController
wrap_parameters :track, :include => :rating
#other controller stuff below
end

在此处查看更多信息: http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html

关于ruby-on-rails-3 - 虚拟属性未移至 params 内的模型哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9354106/

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