在’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
。