新手问题 请教 rails 中 model 中 has_many through 关联中, 是否获取和设置中间表的 API

ji.menbi · June 01, 2017 · Last by ji.menbi replied at June 05, 2017 · 1428 hits
class Author 
  has_many :articles, through: :autor_articles_association
  has_many :author_articles_associations
end

class AuthorArticleAssociation
  belongs_to :author
  belongs_to :article
end

class Article
  has_many :authors, through: :autor_articles_association
  has_many :author_articles_associations
end

现在假设,AuthorAritleAssociation 的 model 里面有一个 column: some_attribute
问题:
1.现在有实例 author 和 article, 那么 在类似 author << article 这种操作过程中,能设置中间表的 some_attribute 属性。类似于这类函数 author.add_articles(article: article, some_attribute: "value")
2.在完成关联的情况下,是否有类似函数 author.author_articles_associations_with(article)
感谢

都寫這樣😫

aa = AuthorArticleAssociation.new
aa.some_attribute = value
aa.author = author
aa.article = article
Reply to hong_xin

额 好吧 难道没有更“优雅”一点的方式了么。。。

縮成一行還是沒有比較優雅...

AuthorArticleAssociation.new(author: author, article: article, some_attribute: value)

求其他人提點不直接操作中間表的方法

Reply to hong_xin

其实 更多的时候这类的应用场景是从 Author 出发 添加一个 Article。中间表在调用中,应该是需要成为一个完全透明的中间层,仅仅提供两者之间的关联属性
所以 总感觉 这种方式太过“丑陋”......不符合 rails 的风格,如果没有的话

Reply to ji.menbi

包進 Model 的 method 中

class Author 
  def add_article(article: nil, some_attribute: nil)
    author_articles_associations.new(article: article, some_attribute: some_attribute)
  end
end

就能這樣用了

author.add_article(article: article, some_attribute: "value")
Reply to hong_xin

嗯 只能这样了

用回调被!

也是一个思路,但是如何解决传参的问题
毕竟中间 model 的参数是与关联的 model 相关的,就代表说,中间层的属性很可能无法从它关联的两个 record 中获取,需要由调用者赋值。

You need to Sign in before reply, if you don't have an account, please Sign up first.