【问题标题】:Rails: form_for with json: undefined method to_model for HashRails:带有json的form_for:哈希的未定义方法to_model
【发布时间】:2016-11-19 08:07:32
【问题描述】:

将我的站点转换为使用 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) } %>

基本上,用form加载partial并传入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.

谢谢。

【问题讨论】:

    标签: ruby-on-rails json hash redis


    【解决方案1】:

    好的,在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 文件以将数据发送回视图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) } %>')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2020-08-29
      • 1970-01-01
      相关资源
      最近更新 更多