为什么我的hidden_​​field被忽略了?没有传递参数

时间:2013-06-21 10:51:52

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

我正在尝试使用Ajax来回切换订阅btn但隐藏的字段根本不做任何事情。我已经尝试设置一个值:4或将表单包装在escape_js中但仍然没有显示出来。

relationship / 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 =&gt; 2}'

RelationshipController for kick:

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

1 个答案:

答案 0 :(得分: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 %>