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

2

1 Answer 1

3

Update this

params.require(:newspaper).permit(:name, :logo, {newspaper_categories_attributes: [ :_destroy, :category_id, :rss_link, :image_url]})
Sign up to request clarification or add additional context in comments.

6 Comments

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
you do not need newspaper_id just NewsPaper.new(paper_params).save newspaper id will be auto assign
Thanks. Now it works. But when i update existing category, it added with new one. It wont be like update or delete and create
use this for update destroy [ :_destroy, :category_id, :rss_link, :image_url, :id] also look to accept the answer:)
Could you elaborate more. Where i need to declare this one?
|

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.