1

I have two classes:

class Post
  has_and_belongs_to_many :receivers
  accepts_nested_attributes_for :receivers
end 

class Receiver
  has_and_belongs_to_many :posts

table schema is like:

posts: id, xxx

receivers: id, email, name, xxxx

posts_receivers: post_id, receiver_id

I pretty much follows the guide here: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

So in my post form, each one could contain several receivers, which are just several email text fields. New receiver records get created automatically from those emails. It would happen that different post form has some existing emails, then I dont want to create new records in receivers table for existing emails. Rather, I would like to find the receiver id with existing email and save the id with post id into posts_receivers table.

Now it just creates new receiver record every time for new posts, no matter the email is an existing one or a new one.

Any suggestion on how to implement this? Thanks a lot!

1 Answer 1

1

Nested attributes don't handle this case for you - they're more intended for when the nested objects belong to the parent object.

You can do this manually by loading up each of your existing receivers in your controller, creating the rest, then assigning them to the post:

def create
  post = Post.new(params[:post])
  post.receivers = params[:receivers].map do |receiver_params|
    Receiver.first_or_create(receiver_params)
  end
  post.save!
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.