我想用 Rails 做一个关于学校学生和课程关系的项目。一个学生可以有很多课程,一个课程可以有很多学生。因此,我认为学生和课程的关系是“多对多”的
我去了控制台:
u = User.first
User Load (0.7ms) SELECT "users".* FROM "users" LIMIT 1
...
c = Course.first
Course Load (0.8ms) SELECT "courses".* FROM "courses" LIMIT 1
...
UserCourseship.create( :user => u, :course => c )
然后我得到的错误是:
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes:user, course
这是我的user.rb
class User < ActiveRecord::Base
has_many :user_courseships
has_many :courses, :through => :user_courseships
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
end
def facebook
@facebook ||= Koala::Facebook::API.new(oauth_token)
end
end
我的course.rb
class Course < ActiveRecord::Base
has_many :user_courseships
has_many :users, :through => :user_courseships
attr_accessible :name, :sn, :time
end
和关系user_courseship.rb
class UserCourseship < ActiveRecord::Base
belongs_to :user
belongs_to :course
attr_accessible :course_id, :user_id
end