1

Here's my code

project.reports << report
project.save

I want to write a single update command instead of these two lines. Something like

project.update(reports << report)

Is there any possible way to do this?

5
  • Was there something like project.create(report) with has_many :reports mapping? Commented Jan 12, 2016 at 17:41
  • 2
    project.reports << report should save both objects I believe Commented Jan 12, 2016 at 17:45
  • @Smar, Mapping already there in model. However, I am implementing this as a part of services. Commented Jan 12, 2016 at 18:02
  • @MichalSzyndel, It seems to be working, but how? Commented Jan 12, 2016 at 18:07
  • Okay in this case @MichalSzyndel is correct... AmanGupta: I guess it worked correctly even first; the API may be a bit unintuitive here. Commented Jan 12, 2016 at 18:09

1 Answer 1

0

If you have association like Project has many Reports, then simply using

project.reports << report

will call save too. No need to call project.save seperately.

Sign up to request clarification or add additional context in comments.

3 Comments

This seems to be a correct answer, but I never saw such thing in rails guide. Can you give me some online reference related to this?
see stackoverflow.com/questions/11043096/… . I also verified it on a local project, it works.
Yeah, that's perfect!

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.