gpt4 book ai didi

ruby-on-rails - rails : form_for with json: undefined method to_model for Hash

转载 作者:可可西里 更新时间:2023-11-01 11:30:34 26 4
gpt4 key购买 nike

将我的站点转换为使用 redis,以便将 JSON 数组而不是 ActiveRecord 数组发送到我的 View 。进行了所有必要的转换,例如 model.attributemodel['attribute'] .

但是,无法弄清楚让我的 form_for 工作。用户可以对游戏进行预测。同_form.html.erb用于创建或更新预测。我得到的错误,undefined method 'to_model' for #<Hash:0x007ff28d5f19c8>发生在这两行上:

_form.html.erb
<%= form_for [game, (prediction || Prediction.new)], remote: true do |f| %>
...
<%= link_to "Delete", [game, prediction], method: :delete, remote: true, class: 'btn btn-xs btn-danger' if prediction.present? %>

有什么想法吗?如果您需要更多信息,请阅读以下内容:

链接和部分:

# index.html.erb
@games.each do |game|
...
<%= prediction_form_link(@predictions, game) %>
<%= render partial: 'predictions/form', locals: { game: game, prediction: prediction_for(@predictions, game) } %>

基本上,用表单加载部分并传入 gameprediction , 还要确定是否 prediction已经存在以更新而不是创建:

def prediction_for(predictions, game)   
predictions["#{game['id']}"].first if predictions["#{game['id']}"].present?
end
def prediction_form_link(predictions, game)
if prediction = prediction_for(predictions, game)
... # code that displays what this button looks like. Partial is loaded in a modal.

谢谢。

最佳答案

好吧,我在 pry 和旧的 SO 帖子上花了很多时间后终于弄明白了。由于我现在要传递 JSON,因此我必须修改 form_for 以使用 OpenStruct,并且非常具体地说明我希望它做什么。基本上必须修改部分和我的 js.erbs。

# _form.html.erb
form_for(OpenStruct.new(prediction || {}), as: :prediction, remote: true, url: (prediction ? game_prediction_path([game['id']], [prediction['id']]) : game_predictions_path(game['id'], Prediction.new)), method: (prediction ? :put : :post) ) do |f| %>
...
<%= link_to "Delete", game_prediction_path([game['id']], [prediction['id']]), method: :delete, remote: true, class: 'btn btn-xs btn-danger' if prediction.present? %>

新的 OpenStruct 以获取现有的 prediction{} 以获得新的。我什至不确定其中哪些是绝对必要的,但它确实有效。分类为一个:prediction,然后指定两种情况(#create#update)的路径、参数和方法,因为我'对两者使用相同的部分。

然后我不得不稍微修改我的 create.js.erbdestroy.js.erbupdate.js.erb 文件将数据发送回 View as_json

# create.js.erb for example
$('#game-<%= @game.id %>').modal("hide");
$('.modal-backdrop').remove();
$('body').removeClass('modal-open');
$('#user-prediction-<%= @game.id %>').html('<%= j prediction_form_link(@predictions.as_json, @game.as_json) %>');
$('#user-prediction-<%= @game.id %>').append('<%= j render partial: "predictions/form", locals: { game: @game.as_json, prediction: prediction_for(@predictions.as_json, @game.as_json) } %>')

关于ruby-on-rails - rails : form_for with json: undefined method to_model for Hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40690617/

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