Note that there are some explanatory texts on larger screens.

plurals
  1. POHow and where to handle the updating process of associated records?
    primarykey
    data
    text
    <p>I am using Ruby on Rails 4 and I would like to properly handle the updating and creating process of associated records through the <code>update_attributes</code> method. That is, I have the following:</p> <pre><code># Model class Article &lt; ActiveRecord::Base has_many :categories accepts_nested_attributes_for :categories end # Controller class ArticlesController &lt; ApplicationController def update @article = Article.find(params[:id]) @article.update_attributes(update_params) ... end private def update_params params.require(:article).permit(:title, ..., :categories_attributes =&gt; [:name, ...]) end end # Logger for the update request Started PATCH "/articles/6" Processing by ArticlesController#update Parameters: {"utf8"=&gt;"✓", "article"=&gt;{"title"=&gt;"Sample title", "categories_attributes"=&gt;{"0"=&gt;{"name"=&gt;"Sample Category 1", "..."=&gt;"..."}, "1"=&gt;{"name"=&gt;"Sample Category 2", "..."=&gt;"..."}, : "..." =&gt; {...}} ... </code></pre> <p>The issue is related to the way Rails handles things for updating associated records in the database, in my case when updating categories through the <code>@article</code> object: when data is submitted so to fire the <code>update</code> action and parameters are passed to the <code>update_attributes</code> method (as shown in the logger above) then Rails creates new category records in the database, one for each element present in the hash <code>categories_attributes</code>.</p> <p>However, <em>my intention is to update existing category records if those exist or create new ones if those do not exist</em>, accordingly to the uniqueness of <code>article_id</code> and <code>name</code> columns in the <code>categories</code> database table, probabily performing a search for data present in these columns in order to check if it is needed to update or create new records. In fact, in the "edit article" view I display a form with input fields for editing categories including fields pre-populated with data related to existing categories and empty fields for categories that can be created "on the fly" by the editor user.</p> <p>How can I properly handle this behavior? Is it model or controller responsability? Or, maybe, is there a better way to manage categories directly in the "edit article" view? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload