0

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

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Ranjith
  • 2,779
  • 3
  • 22
  • 41
  • possible duplicate of [Rails 4 - Strong Parameters - Nested Objects](http://stackoverflow.com/questions/18436741/rails-4-strong-parameters-nested-objects) – Raj Apr 12 '14 at 09:48
  • `@newspaper.newspaper_categoried.build` is a typo, right? – Richard Peck Apr 12 '14 at 09:59

1 Answers1

3

Update this

params.require(:newspaper).permit(:name, :logo, {newspaper_categories_attributes: [ :_destroy, :category_id, :rss_link, :image_url]})
Nitin Jain
  • 3,053
  • 2
  • 24
  • 36
  • See I have one doubt, in my `newspaper_category` table has `4 fields(including newspaper_category of parent (newspaper_id))`. Is that one also required in `newspaper_categories_attributes` – Ranjith Apr 12 '14 at 10:16
  • you do not need `newspaper_id` just `NewsPaper.new(paper_params).save` newspaper id will be auto assign – Nitin Jain Apr 12 '14 at 10:19
  • Thanks. Now it works. But when i update existing `category`, it added with new one. It wont be like `update` or `delete and create` – Ranjith Apr 12 '14 at 10:35
  • use this for update destroy `[ :_destroy, :category_id, :rss_link, :image_url, :id]` also look to accept the answer:) – Nitin Jain Apr 12 '14 at 10:36
  • Could you elaborate more. Where i need to declare this one? – Ranjith Apr 12 '14 at 10:43
  • i think you are using same params for create and update . so just add :id inside newspaper_categories_attributes: array . When your record for newspaper_categories persisted in database then you will receive id as well . so now it will rectify with that id either the record will be updated or it is a new one – Nitin Jain Apr 12 '14 at 11:11