Rails:form_for with json:undefined方法to_model for Hash

时间:2016-11-19 08:07:33

标签: ruby-on-rails json hash redis

将我的网站转换为使用redis,因此将JSON数组发送到我的视图而不是ActiveRecord数组。完成了所有必要的转换,例如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.

谢谢。

1 个答案:

答案 0 :(得分:0)

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

# _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,然后在两种情况下指定路径,参数和方法(#updatecreate.js.erb),因为我对两者使用相同的部分。

然后我必须稍微修改我的destroy.js.erbupdate.js.erbas_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) } %>')

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead