在’has_many“到`关联上使用`find_or_create_by`时出错

我在has_many through关联使用find_or_create_by时遇到问题。

 class Permission < ActiveRecord::Base belongs_to :user belongs_to :role end class Role  :permissions end class User has_many :permissions has_many :roles, :through => :permissions end 

当我在User对象的roles关联上调用find_or_create_by时,Rails会抛出错误。

 u = User.first u.roles.find_or_create_by_rolename("admin") # Rails throws the following error # NoMethodError: undefined method `user_id=' for # 

我能够通过更改我的代码来解决此问题,如下所示:

 unless u.roles.exists?(:rolename => "admin") u.roles << Role.find_or_create_by_rolename("admin") end 

我很想知道find_or_create_by是否through关联与has_many工作。

它有效,但不是:through