我一直在寻找几个小时试图找到一个相互的has_many的最新例子:通过两个实际工作的模型,所以我最终决定我只是问。
我的数据库:
schema.rb
#...
create_table "groups", force: true do |t|
t.string "group_name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "memberships", force: true do |t|
t.integer "student_id"
t.integer "group_id"
end
create_table "students", force: true do |t|
t.string "user_name"
t.string "first_name"
t.string "last_name"
t.string "password_digest"
t.datetime "created_at"
t.datetime "updated_at"
end
#...
我的模特:
student.rb
class Student < ActiveRecord::Base
has_secure_password
validates :password, length: { in: 6..20 }
validates :user_name, format: {with:/\w{2,7}\.\d{1,4}/}, on: :create
validates_uniqueness_of :user_name, on: :create
validates_presence_of :first_name, on: :create
validates_presence_of :last_name, on: :create
has_many :memberships, :dependent => :destroy
has_many :groups, through: :memberships
has_many :ratings, :dependent => :destroy
end
group.rb
class Group < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :students, through: :memberships
validates_uniqueness_of :group_name
end
membership.rb
class Membership < ActiveRecord::Base
belongs_to :students
belongs_to :groups
end
如果我的授权正确地将登录的学生:user_name
放入session[:user_name]
,如果我想要获得该学生所属的所有小组,那么这将是什么( S)?我也有兴趣找到特定群体中的学生。
我试过了:
@current_student = Student.find_by_user_name(session[:user_name])
@current_groups = @current_student.groups
但我得到了:
未初始化的常量Student :: Groups
我做错了什么?
答案 0 :(得分:0)
将membership.rb更改为:
class Membership < ActiveRecord::Base
belongs_to :student
belongs_to :group
end