0
我正在創建RoR應用程序。我有一個名爲'User'的模型。我想創建一個「多對多」的用戶關係。那就是自我參照聯想。Rails - 自我參照協會
我生成與相應的控制器「友誼」模型:
導軌克模型友誼朋友1:整數,FRIEND2:整數,活性:布爾
導軌克控制器友誼創建破壞
點擊「添加好友」後,友誼控制器被稱爲'創建'行動。這個動作應該創建新的'友誼',但是當我點擊'添加朋友'時,出現錯誤:未知屬性'user_id'爲友誼。
下面是代碼,我寫道:
VIEW:(@user是我想添加爲好友,誰一個人)
<%= link_to 'Add friend', create_friendship_path(:friend2 => @user), :method => :post %>
途徑:
post 'create_friendship' => 'friendships#create'
控制器:
class FriendshipsController < ApplicationController
def create
@friendship = current_user.friendships.build(:friend2 => params[:friend2])
if @friendship.save
flash[:notice] = 'Friend added'
else
flash[:error] = 'Friend was not added'
end
end
end
用戶模型:
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, through: :friendships
end
FRIENDSHIP MODEL:
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: 'User'
validates :friend1, presence: true
validates :friend2, presence: true
end
我從來沒有使用Rails的自我指涉的關聯,所以,我無法找到一個錯誤。感謝您的建議。
Schema.rb
ActiveRecord::Schema.define(version: 20150904134846) do
create_table "friendships", force: :cascade do |t|
t.integer "friend1"
t.integer "friend2"
t.boolean "accepted"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "friendships", ["friend1", "friend2"], name: "index_friendships_on_friend1_and_friend2", unique: true
add_index "friendships", ["friend1"], name: "index_friendships_on_friend1"
add_index "friendships", ["friend2"], name: "index_friendships_on_friend2"
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.boolean "admin", default: false
t.string "password_digest"
t.string "remember_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email"
end
發佈您的schema.rb文件。 –
我使用Schema編輯了我的帖子。 RB – simon77