简体   繁体   中英

How do I save an association in a controller?

Trying to accomplish creating an association from the controller and I can't quite get it. Why wouldn't this work?

@document.components = @components.first if @document.automatic_component_selection?

Based in your comment then you have two options:

  • @document.components << @components.first if @document.automatic_component_selection?
  • @document.components.create!(@components.first) if @document.automatic_component_selection?

What you are doing with @document.components = @components.first makes the collection contain only the supplied objects, by adding and deleting as appropriate.

Reference: Rails Guides Active Record Association s

I believe you're trying to add @components.first to that Document object's associated components. In that case, you can write

@document.components << @components.first if @document.automatic_component_selection?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM