【问题标题】:Why is my hidden_field being ignored? Not passing parameter为什么我的 hidden_​​field 被忽略了?不传参数
【发布时间】:2013-06-21 10:51:51
【问题描述】:

我正在尝试使用 Ajax 来回切换订阅 btn 但隐藏字段根本没有做任何事情。我尝试设置 a , value: 4 或将表单包装在 escape_js 中,但仍然没有出现。

关系/destroy.js.erb:

$("#unfollow_<%=@user.id%>").replaceWith('<div id="follow_<%=@user.id%>"><%=
form_for(current_user.relationships.build(followed_id: @user.id), remote: true) do |f|
f.hidden_field :followed_id
f.submit "Subscribe"
end
%></div>')

日志:

Started POST "/relationships" for 127.0.0.1 at 2013-06-21 05:38:46 -0400
Processing by RelationshipsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Jx9SG25KLJH5UfstrOw3RudtgqJtKwidvT4xGt+bqas=", "commit"=>"Subscribe ∞"}
User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = '1gPcW8-7ey4aSGV-g1O_lw' LIMIT 1
Completed 500 Internal Server Error in 2ms
NoMethodError (undefined method `[]' for nil:NilClass):
app/controllers/relationships_controller.rb:6:in `create'

POST 缺少此参数(html 中也缺少输入):

"relationship"=>{"followed_id"=>"46"}
<input id="relationship_followed_id" name="relationship[followed_id]" type="hidden" value="92" />

当我尝试时:

f.hidden_field followed_id: @user.id

我得到未定义的方法 `{:followed_id=>2}' for #

RelationshipController 用于踢球:

def create
  @user = User.find(params[:relationship][:followed_id])
  current_user.follow!(@user)
  respond_to do |format|
    format.html { redirect_to :back }
    format.js
  end
end

def destroy
  @user = Relationship.find(params[:id]).followed
  current_user.unfollow!(@user)
  respond_to do |format|
    format.html { redirect_to :back }
    format.js
  end
end

【问题讨论】:

标签: ajax ruby-on-rails-3 jquery hidden-field


【解决方案1】:

另类

另存为_partial_form.html.erb

  <div id="follow_<%=@user.id%>">
    <%= form_for(current_user.relationships.build(followed_id: @user.id), remote: true) do |f| %>
    <%= f.hidden_field :followed_id %>
    <%= f.submit "Subscribe" %>
    <%= end %>
  </div>

在你的 js.erb 中

  $(selector).replaceWith('<%= j render 'path to your partial_form'%>')

并确保您的followed_id 具有价值,以产生测试价值,

<%= f.hidden_field :followed_id, :value => 18 %>

【讨论】:

  • 这种方法有什么不同?这只是JS文件中的语法问题吗?我以为我之前尝试过部分方法
猜你喜欢
  • 2013-09-30
  • 2016-06-20
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 2022-12-23
  • 1970-01-01
  • 2021-08-23
相关资源
最近更新 更多