Ruby / Rails:friend_id未添加到友谊表中

时间:2014-08-23 04:28:34

标签: ruby-on-rails associations jointable

使用Rails 4.1.4框架。在下面的user_friendships表中添加'friend_id'时遇到问题...当程序在rails中运行时,我被重定向到根(如预期的那样)并给出成功消息,即友谊已创建。但是,当我打开数据库GUI时,我看到只有user_id被保存到user_id列中,而且friend_id列总是保留为'nil',无论是谁的朋友。我一直在寻找高低 - 我知道这一定是简单的事情,这让我发疯了。任何帮助深表感谢!

任何人都可以看到我在代码中犯的错误会阻止它被保存吗?对于friend_id来说,这可能是一个缺失的强参数问题,如果是这样,我该如何纠正呢?

模特:

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'

控制器:

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查看文件--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 %>

- 个人资料页面上方表单的提交按钮

<div class="page-header">
    <h1> <%= @user.full_name%> </h1>
    <%= link_to "Add Friend", new_user_friendship_path(friend_id: @user), class:'btn'%>
</div>

1 个答案:

答案 0 :(得分:1)

profile_name出现问题。我不知道它是什么,但应该是id。因此,在控制器更改模型中搜索到:

@friend = User.find_by_id(params[:user_friendship][:user_id])

在模板<%= f.hidden_field :friend_id, value: @friend.id %>

This works for me

但是,如果你使用的是friendly_id gem,或者其他强迫你使用profile_name而不是id的东西,你也应该在其他地方使用它,比如链接:

new_user_friendship_path(friend_id: @user.profile_name)

也许这会有所帮助。