Rails Nested Attributes 的一个问题

anklos · February 26, 2016 · Last by anklos replied at February 29, 2016 · 2661 hits

我有 2 个类

class Post
  has_and_belongs_to_many :receivers
  accepts_nested_attributes_for :receivers
end 
class Receiver
  has_and_belongs_to_many :posts

表的设计是: posts: id, xxx

receivers: id, email, name, xxxx

posts_receivers: post_id, receiver_id

完全遵循这个 http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

在我的 form 里,每个 post 都会填上几个 receiver,有时候会有同一个的 receiver 的 email 在不同的 post 里出现。这个时候我不希望我的 receiver 表中对同样的 email 新建 record(因为 nested attributes 每次会自动新建一个 receiver),而是在posts_receivers表中根据已有的 email 的 receiver id 去建新的 record 来存储新的 post 和已有的 receiver 的关系。

请教有什么比较好的方法能实现呢?非常感谢!

没大看明白你的问题,另外推荐优先使用 has_many through而非 has_and_belongs_to_many

好像类似文章推送。不使用嵌套属性。传接收者的参数,在 controller 判断接收者存不存在,存在就取 id,不存在就新建然后再新建中间表 post 和 receiverid 的对应记录

#2 楼 @pathbox 顶楼上,楼主希望 post 和 receiver 都是唯一,那表单添加 receiver 的 email 时(或者 save 之前)就需要手工判断是否已经存在啊。不然 rails 是不会自动给你取查找,这个 email 是否已经存在了。。。毕竟,给的不是 ID。。。

#3 楼 @mr_night 是的。判断是否存在,再决定是返回已存在的 id 还是新建一个 id。但不知道怎么在 nested attribute 里面做。

要不然就如@pathbox 说的,自己写代码新建 post_id receiver_rid 的记录。

#1 楼 @qinfanpeng 原因是什么啊?

#5 楼 @anklos

Rails Guides says that “You should use has_many :through if you need validations, callbacks, or extra attributes on the join model”. - See more at: http://blog.flatironschool.com/why-you-dont-need-has-and-belongs-to-many/#sthash.WXKB4UlF.dpuf

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