Thanks for visiting
Whenever I click on Add a friend I get "friend added" but upon checking my console it says Friendship id: 10, user_id: 2, friend_id: 0, created_at: "2015-09-11 05:05:27", updated_at: "2015-09-11 05:05:27"> meaning it's adding but not associating with a friend_id. Can someone help me figure out why it's not saving friend_id whenever I click add a friend. Thank you for all your help.
Schema.rb
create_table "friendships", force: true do |t|
t.integer "user_id"
t.integer "friend_id"
t.datetime "created_at"
t.datetime "updated_at"
end
Routes.rb
root "users#index"
resources :friendships, only: [:create, :destroy]
resources :sessions, only: [:new, :create, :destroy]
resources :users
Users/show
<% @users.each do |user| %>
<% if user.user_name != current_user.user_name %>
<% if @friendshiplink.nil? %>
<%= user.user_name %>
<%= link_to "Add Friend", friendships_path(friend_id: user), method: :post %>
<% else %>
<%= link_to(
("Unfollow"),
"/friendships/#{ @friendshiplink.id }",
method: :delete) %>
<% end %>
<% end %>
<% end %>
User Model
has_many :friendships
has_many :friends, through: :friendships
has_many :inverse_friendships, class_name: "Friendship", foreign_key: "friend_id"
has_many :inverse_friends, through: :inverse_friendships, source: :user
Friendship Model
belongs_to :user
belongs_to :friend, class_name: "User"
User Controller
def show
@users = User.all
@user = User.friendly.find(params[:id])
current_user
if @current_user
@followerlink = Follower.where(leader_id: @user.id,
follower_id: @current_user.id).first
@friendshiplink = Friendship.where(user_id: @user.id,
friend_id: @current_user.id).first
end
end
Friendship Controller
def create
@friendship = current_user.friendships.build(friend_id: params[:friend_id])
if @friendship.save
flash[:notice] = "Added friend."
redirect_to root_url
else
flash[:error] = "Unable to add friend."
redirect_to root_url
end
end
def destroy
@friendship = current_user.friendships.find(params[:id])
@friendship.destroy
flash[:notice] = "Removed friendship."
redirect_to current_user
end
def friendship_params
params.require(:friendship).permit(:friend_id, :user_id)
end
Thanks again for all the help. If there are any question or I'm missing a part of my code which may be needed, Please ask.
Aucun commentaire:
Enregistrer un commentaire