Reputation: 53
I wanted to create twitter like followers and following thing. in my view i have
<% if current_user.following?(@otheruser) %>
<%= render 'unfollow' %>
<% else %>
<%= render 'follow' %>
<% end %>
in _follow.html.erb
<%= form_for (@otheruser), url: createfollower_path(@otheruser) ,:class=>"form-horizontal",method: :post do |f| %>
<%= f.hidden_field :user_id, :value => @otheruser.id %>
<%= f.submit "Follow", class: "btn btn-primary" %>
<% end %>
in controller create action
def create
user = User.find(params[:user_id])
current_user.follow(user)
redirect_to followuser_url
end
in user.rb
has_many :followers, class_name: "Relationship" #-> users following you
has_many :following, class_name: "Relationship", foreign_key: :follower_id, foreign_key: :user_id
def follow(other_user)
relationships.create(user_id: other_user.id)
end
in relationship.rb
class Relationship < ActiveRecord::Base
belongs_to :user
belongs_to :follower, class_name: "User"
validates :user, :follower, presence: true
validates :user_id, uniqueness: { scope: :follower_id }
end
now when I am trying to submit the follow button it is showing error as "Couldn't find User with 'id'=" and parameters are
{"utf8"=>"✓","authenticity_token"=>"681q5ft03+WRdqgHagh/gI1mV3uohwaEj1sF8zdTycUAN5yTiVMT/wGCV4tLPRVRRFRA+6mYSS1bXk2ormA/zw==",
"user"=>{"user_id"=>"7"},
"commit"=>"Follow",
"format"=>"7"}
Upvotes: 0
Views: 120
Reputation: 10388
You need to rewrite your controller's create action
.
def create
user = User.find(params[:user][:user_id])
current_user.follow(user)
redirect_to followuser_url
end
Should worked !!!
Upvotes: 1