2014-01-10 55 views
0

當我嘗試訪問Users類的'groups'或'members'屬性時,我得到一個未定義的成員方法錯誤。 (注:我知道,我需要重新定義我的會員類爲單數,那是次要的,爲什麼它的分解與開始搞清楚)爲什麼這個ActiveRecord關係不起作用?

我有一個用戶類,如下所示:

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
    has_many :group, :through => :member 
end 

會員等級:

class Members < ActiveRecord::Base 
    belongs_to :group 
    belongs_to :user 
end 

組類:

class Group < ActiveRecord::Base 
    has_many :users, :through => :members 
end 

幷包含一個模式:

create_table "groups", force: true do |t| 
    t.string "group_name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

create_table "members", force: true do |t| 
    t.integer "group_id" 
    t.integer "user_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

add_index "members", ["group_id"], name: "index_members_on_group_id" 
add_index "members", ["user_id"], name: "index_members_on_user_id" 

create_table "users", force: true do |t| 
    t.string "email",     default: "",  null: false 
    t.string "encrypted_password",  default: "",  null: false 
    t.string "reset_password_token" 
    t.datetime "reset_password_sent_at" 
    t.datetime "remember_created_at" 
    t.integer "sign_in_count",   default: 0,  null: false 
    t.datetime "current_sign_in_at" 
    t.datetime "last_sign_in_at" 
    t.string "current_sign_in_ip" 
    t.string "last_sign_in_ip" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.string "role",     default: "user" 
end 

add_index "users", ["email"], name: "index_users_on_email", unique: true 
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 

回答

3

你缺少has_many的加入模型在UserGroup模型。

添加has_many :membersUserGroup模型類的定義:

用戶模型:

class User < ActiveRecord::Base 
    ... 
    has_many :members 
    has_many :groups, :through => :members 
end 

注意,在你的User模型,你有has_many :group, :through => :member。由於您正在定義關係,因此您的關聯符號也必須是複數形式。

組型號:

class Group < ActiveRecord::Base 
    has_many :members 
    has_many :users, :through => :members 
end 

隨着class_name選項如果你想繼續Members類名Members(複數):

是的,你應該考慮根據conventi將Members模型重命名爲Member上。但是,如果您仍想保留複數或其他任何名稱,則可以在has_many聲明中指定class_name選項,以便類名的符號映射正確。所以,你的UserGroup模型需要被更新爲:

用戶模型:

class User < ActiveRecord::Base 
    ... 
    has_many :members, class_name: 'Members' 
    has_many :groups, :through => :members 
end 

組型號:

class Group < ActiveRecord::Base 
    has_many :members, class_name: 'Members' 
    has_many :users, :through => :members 
end 
+0

現在,我已經得到了關係問題解決了,我實際上將它重新命名爲'Membership',並且'Membersh' ips'作爲表名。不過,感謝您的幫助。 – RonLugge