我想使用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
謝謝!有用! – 2012-08-02 14:51:10