【发布时间】:2014-12-04 18:55:43
【问题描述】:
我正在尝试在用户中对我的应用程序实施关注/取消关注功能。我正在使用 devise + omniauth 并使用单独的用户控制器。当我单击关注按钮时,它不会对应该计算关注/关注者等的数字做任何事情。在控制台中我收到这些错误
Processing by RelationshipsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ReTtZn0GbB7f5LROr6FLnw40ErDDcubDa8/yLnyVd/FIhxM3qjZI8pjYDAGmuGJiv1paGVjhp/LMVmFtkcZVwQ==", "followed_id"=>"1", "commit"=>"Follow"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 2]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
WARNING: Can't mass-assign protected attributes for Relationship: followed_id
app/models/user.rb:21:in `follow'
app/controllers/relationships_controller.rb:7:in `create'
(0.1ms) commit transaction
Relationship Load (0.3ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."follower_id" = ? AND "relationships"."followed_id" = ? LIMIT 1 [["follower_id", 2], ["followed_id", 1]]
Rendered users/_unfollow.html.erb (11.5ms)
Rendered relationships/create.js.erb (13.9ms)
Completed 500 Internal Server Error in 38ms
ArgumentError (First argument in form cannot contain nil or be empty):
app/views/users/_unfollow.html.erb:1:in `_app_views_users__unfollow_html_erb___2456782614560778317_70319555077280'
app/views/relationships/create.js.erb:1:in `_app_views_relationships_create_js_erb__3841758023410302021_45366420'
app/controllers/relationships_controller.rb:8:in `create'
我的代码行如下
relationship_controller
class RelationshipsController < ApplicationController
before_filter :authenticate_user!
def create
@user = User.find(params[:followed_id])
current_user.follow(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
def destroy
@user = Relationship.find(params[:id]).followed
current_user.unfollow(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
end
_follow_form.html.erb
<div id="follow_form">
<% if current_user.following?(@user) %>
<%= render 'unfollow' %>
<% else %>
<%= render 'follow' %>
<% end %>
</div>
_unfollow.html.erb
<%= form_for(current_user.active_relationships.find_by(followed_id: @user.id),
html: { method: :delete },
remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn" %>
<% end %>
创建/销毁 .js.html
$("#follow_form").html('<%= escape_javascript(render('users/unfollow')) %>')
$("#followers").html('<%= @user.followers.count %>')
$("#follow_form").html('<%= escape_javascript(render('users/follow')) %>')
$("#followers").html('<%= @user.followers.count %>')
提前谢谢你..我很想弄清楚这个......
编辑了我的错误引用
【问题讨论】:
-
在 Rails 4 中,您必须将参数列入白名单。使用以下命令: def private_params params[:yourmodel] permit(:yourkeys, :anotherkey] end
标签: ruby-on-rails-4 devise relationship