添加好友时无法关联两个用户

时间:2015-09-11 12:26:32

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 associations

感谢您访问

每当我点击添加朋友时,我都会添加"朋友添加"但在检查我的控制台时,它显示友谊ID:10,user_id:2,friend_id:0,created_at:" 2015-09-11 05:05:27",updated_at:" 2015-09- 11 05:05:27">意思是它添加但不与friend_id相关联。有人可以帮我弄清楚为什么每当我点击添加朋友时它都不会保存friend_id。谢谢你的帮助。

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.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 %>

用户模型

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

友谊模式

belongs_to :user
belongs_to :friend, class_name: "User"

用户控制器

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

友情控制器

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

再次感谢所有帮助。如果有任何问题,或者我错过了可能需要的部分代码,请询问。

1 个答案:

答案 0 :(得分:1)

这可能不是问题,但试一试:

<script>
    var editor = CodeMirror.fromTextArea(document.getElementById("html"), {
        lineNumbers: true,
        mode: "text/html",
        matchBrackets: true
    });
</script>

OR

<%= link_to "Add Friend", friendships_path(friend_id: user.id), method: :post %>

另外,为了确保错误,请在<%= link_to "Add Friend", { action: :create, controller: 'friendship',:friend_id => user.id }, method:"post" %>

中添加params

更新:以最简单的方式执行

console