0

我正在尝试使用 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 #

踢球的关系控制器:

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
4

1 回答 1

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 %>
于 2013-06-21T11:16:58.270 回答