【问题标题】:Rails-4.2 delete a 'through' assocationRails-4.2 删除“通过”关联
【发布时间】:2015-07-02 18:53:28
【问题描述】:

在两个主表的索引值已知的情况下,销毁/破坏关联的最简单语法是什么?

User has_many roles through clearances
Role has_many users through clearances

Clearance[.id, .user_id, .role_id]
Role[.id, .rolename]
User[.id, .username]

username == 'auser'
rolename == 'arole'

我希望删除连接这两个值的间隙行,但不要触及任何一个主表。

2015-07-08 适合我的解决方案是:

  mu = User.find_by!( :username => uname )
  mr = Role.find_by!( :rolename => rname )
  rc = mu.authorisations.find_by( :role_id => mr.id )
  rc.delete if rc

@Hristo 下面的建议导致了这个错误:

SQLite3::SQLException: 没有这样的列:authorisations.username: SELECT "authorisations".* FROM "authorisations" WHERE "authorisations"."username" = 'xtra_user' AND "authorisations"."rolename" = 'test_role' (ActiveRecord::StatementInvalid)

注意因为这是一个正在积极开发的项目,所以术语清除 被授权取代,模型重命名和编辑 相应地。

正如在原始问题中所指出的,连接表只有 belongs_to 模型的引用 id 值。

【问题讨论】:

  • 我回答你的问题了吗? :)
  • 谢谢。你可能有,但我没有机会证明这一点。出于某种原因,我没有收到您回复的电子邮件,仅用于您的跟进。我必须继续解决问题。一旦我证明这个公式确实有效,我就会将 Q 标记为已回答。

标签: ruby-on-rails-4 rails-activerecord model-associations


【解决方案1】:
Clearance.where(age: "auser", rolename: "arole").destroy_all

Clearance.destroy_all(age: "auser", rolename: "arole")

应该能做到,而且够短。

【讨论】:

  • 不,这不起作用。我使用的解决方法是:
猜你喜欢
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多