I am new to ruby on rails espacially nestes forms. I am trying to create an author and a book in the same form knowing that there's a many to many relationshio between them my code is presented below. book.rb
class Book < ActiveRecord::Base
has_many :exemplaires
has_many :talks, inverse_of: :book
has_many :subjects, through: :writings
has_many :writings
has_many :authors, through: :talks
accepts_nested_attributes_for :authors
validates :title, presence: true
end
author.rb:
class Author < ActiveRecord::Base
has_many :talks
has_many :books, through: :talks
end
talk.rb
class Talk < ActiveRecord::Base
belongs_to :book
belongs_to :author
end
book_controller.rb
class BooksController < ApplicationController
def index
end
def list
@books= Book.all
end
def new
@book = Book.new
@[email protected]
end
def create
@book= Book.new(book_params)
if @book.save
flash[:notice]='goood'
redirect_to admin_manage_path
else
flash[:alert]='ouups'
redirect_to root_url
end
end
private
def book_params
params.require(:book).permit(:title, :pages, :resume, :authors_attributes)
end
end
books\new.html.erb
<h1>Add new book</h1>
<%= form_for(@book) do |form| %>
<%= form.label :title %>
<%= form.text_field :title %>
<%= form.fields_for :authors do |tag_form| %>
<%= tag_form.label :f_name %>
<%= tag_form.text_field :f_name %>
<% end %>
<%= form.submit "Submit" %>
<% end %>
what i got as error
Processing by BooksController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"qpGng8tOiC/B5VX2tphuhAe+Wq1vx7it1vEO6XmwZmI=", "book"=>{"title"=>"booooooooooooook", "authors_attributes"=>{"0"=>{"f_name"=>"auuuuuuuuuuuuuuuuuthor"}}}, "commit"=>"Submit"} Unpermitted parameters: authors_attributes
You need to whitelist the authors_attributes
fields too:
def book_params
params.require(:book).permit(:title, :pages, :resume, authors_attributes: [:f_name])
end