5
Występuje problem z korzystaniem z find_or_create_by
w skojarzeniu has_many
through
.Błąd podczas używania `find_or_create_by` w skojarzeniu` has_many`` through`
class Permission < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class Role < ActiveRecord::Base
# DB columns: user_id, role_id
has_many :permissions
has_many :users, :through => :permissions
end
class User
has_many :permissions
has_many :roles, :through => :permissions
end
Szyny zgłasza błąd, kiedy powoływać find_or_create_by
na roles
związku z User
obiektu.
u = User.first
u.roles.find_or_create_by_rolename("admin")
# Rails throws the following error
# NoMethodError: undefined method `user_id=' for #<Role id: nil, rolename: nil,
# created_at: nil, updated_at: nil>
udało mi się obejść ten problem poprzez zmianę mój kod w następujący sposób:
unless u.roles.exists?(:rolename => "admin")
u.roles << Role.find_or_create_by_rolename("admin")
end
Jestem ciekaw czy find_or_create_by
współpracuje z has_many
through
skojarzeń.
Tak, problem ogranicza się do: przez. Zaktualizuję pytanie, aby to odzwierciedlić. –
Nie sądzę, że dostaniesz więcej odpowiedzi na ten temat. Metody 'find_or _...' nie powinny działać ze skojarzeniami ': through'. Jedynym sposobem, w jaki można go uruchomić, byłoby usunięcie modelu 'Permission' i użycie relacji' has_and_belongs_to_many' z prostą tabelą mapowania. –
Wywołania, takie jak 'u.roles.find_by_rolename (" admin ")' działa z 'has_many: through'. Pomyślałem, że 'u.roles.find_or_create_by_rolename (" admin ")' może działać. Czy możesz wskazać mi dokumentację, w której określono to zastrzeżenie? –