Using the Rails 4.1.4 framework. Having a problem adding a 'friend_id' to the user_friendships table below... when the program runs in rails, I am redirected to the root (as expected) and given the success message that the friendship was created. However, when I crack open the database GUI, I see that only a user_id is saved into the user_id column, and the friend_id column is always left 'nil', no matter who friends who. I've searched high and low - I know it must be something simple and it's driving me crazy. Any help is much appreciated!
Can anyone see the mistake I may have made in the code that would prevent this from being saved? Could it be a missing strong parameters issue for friend_id, and if so, how do I go about correcting it?
The Models:
class User < ActiveRecord::Base
has_many :user_friendships
has_many :friends, through: :user_friendships
class UserFriendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: 'User', foreign_key: 'friend_id'
The Controller:
class UserFriendshipsController < ApplicationController
before_filter :authenticate_user!, only: [:new]
def new
if params[:friend_id]
@friend = User.where(profile_name: params[:friend_id]).first
raise ActiveRecord::RecordNotFound if @friend.nil?
@user_friendship = current_user.user_friendships.new(friend: @friend)
else
flash[:error] = 'Friend required.'
end
rescue ActiveRecord::RecordNotFound
render file: 'public/404', status: :not_found
end
def create
if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id)
@friend = User.where(profile_name: params[:user_friendship][:friend_id]).first
@user_friendship = current_user.user_friendships.new(friend: @friend)
@user_friendship.save
redirect_to root_path
flash[:success] = "You are now friends." #{@friend.full_name}
else
flash[:error] = 'Friend required.'
redirect_to root_path
end
end
user_friendships view files --new.html.erb
<% if @friend %>
<h1> <%= @friend.full_name %> </h1>
<p> Do you really want to become friends with <%= @friend.full_name %>?</p>
<%= form_for @user_friendship, method: :post do |f| %>
<div class="form form-actions">
<%= f.hidden_field :friend_id, value: @friend.profile_name %>
<%= submit_tag "Yes, Add Friend", class: 'btn btn-primary' %>
<%= link_to "Cancel", profile_path(@friend), class: 'btn' %>
</div>
<% end %>
<% end %>
-- submission button for form above on profile page
<div class="page-header">
<h1> <%= @user.full_name%> </h1>
<%= link_to "Add Friend", new_user_friendship_path(friend_id: @user), class:'btn'%>
</div>