Igor Martins
Igor Martins

Reputation: 2047

How to save follower data?

I have a table user_followers that has: user_id and follower_id

I'm trying to save a new record where the logged in user follows another user via AJAX.

this is the button:

<%= link_to "Add friend", teste_user_follower_path(:params => @friend.id), remote: true, class: 'btn' %>

And the action teste where I try to save:

def teste

if params[:query]
  @friend = User.where(id: params[:query]).first
  @user_follower = current_user.user_followers.new(follower: @friend)
else
  flash[:error] = "Friend required"
end

end

I have the associantions set up correctly I think

Upvotes: 0

Views: 49

Answers (2)

Antoine
Antoine

Reputation: 2807

You are not actually creating anything in your code. Here is the documentation about associations: http://guides.rubyonrails.org/association_basics.html#detailed-association-reference

You should do something like:

@user_follower = current_user.user_followers.create(follower: @friend)

Upvotes: 1

Kyle Decot
Kyle Decot

Reputation: 20815

If you're creating a record I assume that you've set up your teste route as POST. If this is the case you'll have to add method: :post to your link_to

<%= link_to "Add friend", teste_user_follower_path(:params => @friend.id), method: :post, remote: true, class: 'btn' %>

It also doesn't look like you're actually saving the record anywhere. You're calling new but never calling save. If you want to do both at once you can use create

def teste
  if params[:query]
    @friend = User.where(id: params[:query]).first
    @user_follower = current_user.user_followers.create(follower: @friend)
  else
    flash[:error] = "Friend required"
  end
end

Upvotes: 1

Related Questions