Ranjith
Ranjith

Reputation: 2819

How to insert nested form values into DB

I am using Rails 4.

In my project, include nested form for has_many relationship. From UI point of view, I got it. But nested form values are not inserting into database.

class Newspaper < ActiveRecord::Base
    has_to :newspaper_categories, :dependent_destroy => true
    accepts_nested_attributes_for :newspaper_categories, :allow_destroy => true, :reject_if => :all_blank
end

class NewspaperCategory < ActiveRecord::Base
    belongs_to :newspaper
end

Newspaper form contents like,

<%= nested_form_for(@newspaper) do |f| %>

     # Newspaper form fields

     # Include `Newspaper category` form from the file.
    <%= f.fields_for :newspaper_categories do |nc|%>
         <%= render "newspaper_category"  %>
    <% end %>

    # For add new form using JS
    <%= f.link_to_add "Add New", :newspaper_categories %>

    <%= f.submit %>
<% end %>

In my Newspaper Controller,

# add build in new method,
def new
   @newspaper = Newspaper.new
   @newspaper.newspaper_categoried.build
end

# In params set task_attributes,
def newspaper_params
   params.require(:newspaper).permit(:name, :logo, task_attributes[:cat_link, :_destroy])
end

Where I goes wrong, still i'm confusing to insert

Upvotes: 0

Views: 335

Answers (1)

Nitin Jain
Nitin Jain

Reputation: 3083

Update this

params.require(:newspaper).permit(:name, :logo, {newspaper_categories_attributes: [ :_destroy, :category_id, :rss_link, :image_url]})

Upvotes: 3

Related Questions