I have a scenario where my application interacts with three models called User, Question and Answer. I added three questions for a user from admin panel or through rails console. Now in separate action i need to display all the questions of a particular user and providing a option of adding multiple answers as text for each. I don't know how to proceed further. Here is my sample code which i tried.
class User
has_many :questions
accepts_nested_attributes_for :questions
end
class Question
belongs_to :user
has_many :answers
accepts_nested_attributes_for :answers
end
class Answer
belongs_to :question
end
users_controller.rb
class UserController
def display_questions
#user = current_user
end
end
views/display_questions.html.erb
<%= form_for #user do |f| %>
<%= f.fields_for :questions do |q| %>
<%= q.fields_for :answers do |a| %>
<%= a.text_field :name %>
<% end %>
<%= q.link_to_add 'Add', :answers %>
<% end %>
<% end %>
I am getting all the questions for that user but not able to add answers for individual question. I am confused how to build nested fields for these scenario, any help is appreciated. Thanks
If you use the nested_form gem it's pretty easy, just do:
<%= nested_form_for #user do |f| %>
<%= f.fields_for :questions do |q| %>
<%= q.fields_for :answers do |a| %>
<%= a.text_field :name %>
<% end %>
<%= q.link_to_add 'Add', :answers %>
<% end %>
<% end %>
Note the nested_form_for instead of form_for
Also, you will need to add the property accepts_nested_attributes_for for the models which correspond:
class User < ActiveRecord::Base
has_many :questions
accepts_nested_attributes_for :questions
end
class Question < ActiveRecord::Base
belongs_to :user
has_many :answers
accepts_nested_attributes_for :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
end
Related
This is part of my app in rails:
How to get values in the controller of posts from the check boxes?
I want to get the array of ids got from the check boxes.
The post is created, but I can not access the array of ids got from the check boxes.
class Categoryofpost < ActiveRecord::Base
belongs_to :post
belongs_to :category
end
............................
In views/posts/new.html.erb
<%= form_for #post do |p| %>
<%= p.label :title %>
<%= p.text_field :title %>
<br>
<%= p.label :body %>
<%= p.text_area :body %>
<br>
<p>Related to : </p>
<br>
<%= p.collection_check_boxes :category_ids, Category.all, :id, :name %>
<br>
<%= p.submit "Create" %>
<% end %>
class Category < ActiveRecord::Base
belongs_to :user
validates :name, uniqueness: true
has_many :categoryofposts
has_many :related_posts, class_name: "Post", through: :categoryofposts , source: :post
end
....................
In the posts controler
def create
#post_params = post_params
##post_params[:user_id] = 1 #session[:user_id]
#post = Post.new(#post_params)
if #post.save
# #cat = get_categories
# #cat.each do |c|
# Categoryofpost.create(post_id: #post.id, category_id: c)
# end
redirect_to #post, notice: "The post has been posted successfully."
else
render action: :new, alert: "The post has not been posted."
end
end
protected
def post_params
params.require(:post).permit(:title, :body, categoy_ids: [])
end
def get_categories
params.require(:post).permit(categoy_ids: [])
end
class Post < ActiveRecord::Base
belongs_to :user, dependent: :destroy
has_many :categoryofposts
has_many :categories, through: :categoryofposts
end
You have a typo in your post_params method.It should be
def post_params
params.require(:post).permit(:title, :body, category_ids: [])
end
Notice category_ids.
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
#author=#book.authors.new
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
I am using rails 4.0.4 with nested_form 0.3.2 to build an app that allows users to organize movies in lists.
I have these main models, a List model (I've excluded things such as validations):
class List < ActiveRecord::Base
belongs_to :user
has_many :list_movie_pairs
has_many :movies, :through => :list_movie_pairs
accepts_nested_attributes_for :list_movie_pairs, :allow_destroy => true
accepts_nested_attributes_for :movies, :allow_destroy => true
end
A Movie model:
class Movie < ActiveRecord::Base
has_many :list_movie_pairs
has_many :lists, :through => :list_movie_pairs
has_many :reviews
end
A ListMoviePair model for the many-to-many relationship:
class ListMoviePair < ActiveRecord::Base
belongs_to :list
belongs_to :movie
validates_presence_of :list_id, :movie_id
validates_uniqueness_of :movie_id, scope: :list_id
end
I am trying to build an interface for the user to add movies to a created list. These routes serve my purpose:
get "/users/:username/lists/:id/add" => "lists#add_movies", :as => :user_list_list_movie_pairs
post "/users/:username/lists/:id/add" => "lists#submit_movies"
These are the classes in my ListsController that should make this possible:
def add_movies
#pair = list.list_movie_pairs.new # "list" is a helper that returns the current list
end
def submit_movies
#list = current_user.lists.find(params[:id])
#pair = #list.list_movie_pairs.new(pair_params)
if #pair.save
redirect_to user_list_path(current_user.username, #list)
else
render :add_movies
end
end
def list_params
params.require(:list).permit(:name, :description, :private, \
list_movie_pairs_attributes: [:id, :list_id, :movie_id, :_destroy], \
movies_attributes: [:id, :title, :_destroy])
end
And this is the form in my view
<%= nested_form_for [current_user, list, #pair] do |f| %>
<%= f.fields_for :movies do |movie_form| %>
<%= movie_form.text_field :title %>
<%= movie_form.link_to_remove "Remove movie" %>
<% end %>
<%= f.link_to_add "Add movie", :movies %>
<% end %>
I get this error when trying to access the view:
Invalid association. Make sure that accepts_nested_attributes_for is used for :movies association.
Which pops at this line:
<%= f.link_to_add "Add movie", :movies %>
Note 1: I am using the Devise gem for users, hence the "current_user" helper;
Note 2: I have tried using both "movies" and "list_movie_pairs", i.e.:
f.fields for :list_movie_pairs
and
f.link_to_add "Add movie", :list_movie_pairs
in my view, neither association seems to work
Your code in the view should be like this
<%= nested_form_for [current_user, list, #pair] do |f| %>
<%= f.fields_for :movies do |movie_form| %>
<%= movie_form.text_field :title %>
<%= movie_form.link_to_remove "Remove movie" %>
<%= movie_form.link_to_add "Add movie", :movies %> #note the change here
<% end %>
<% end %>
Update
There are several issues in your code
1.In your List model,this line is not required
accepts_nested_attributes_for :movies, :allow_destroy => true #not requied
2.In your ListsController,you have this line
#pair = #list.list_movie_pairs.new(pair_params)
It should be
#pair = #list.list_movie_pairs.new(list_params) because you have list_params method not pair_params
Maybe I still do not understand how Rails 4 works with has_many and belongs_to association.
My form doesn't save the has_many relationship
Entry Model
class Entry < ActiveRecord::Base
belongs_to :survey
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers
end
Answer Model
class Answer < ActiveRecord::Base
belongs_to :entry
validates :content, presence: true
validates :entry_id, presence: true
end
Entry Controller
def create
#answer = Entry.create(params.require(:entry).permit(:survey_id, answers_attributes [:content, :entry_id]))
redirect_to '/'
end
Form
<%= form_for(:entry, :url => {:controller => 'entrys', :action => 'create'}) do |q| %>
<%= q.hidden_field :survey_id, :value => #survey.id %>
<%= q.fields_for :answer do |a| %>
<%= a.text_field :content %>
<% end %>
<%= q.submit :Save %>
<% end %>
Debug error
Parameters: {"utf8"=>"✓", "authenticity_token"=>"**********************=", "entry"=>{"survey_id"=>"1", "answer"=>{"content"=>"asdasd"}}, "commit"=>"Save"}
Unpermitted parameters: answer
(0.1ms) begin transaction
Thanks in advance.
Update fields_for in your form as below:
<%= q.fields_for :answers do |a| %>
<%= a.text_field :content %>
<% end %>
Note pluralized :answers and not :answer.
As Entry model is associated to Answer in a 1-M Relationship, you should be using plural :answers in fields for.
Right now as you used :answer (singular), it wasn't interpreted by rails correctly, so you received answer key in params hash instead of receiving answers_attributes which obviously resulted in warning as Unpermitted parameters: answer
UPDATE
Update the create action as below:
def create
#answer = Entry.create(params.require(:entry).permit(:survey_id, answers_attributes: [:content, :entry_id]))
redirect_to '/'
end
It should be answers_attributes: [:content, :entry_id] and not answers_attributes [:content, :entry_id] (Notice missing :)
Also, I would suggest you to update your Entry Controller new action as below:
def new
#entry = Entry.new
#entry.answers.build
end
After this update the form_for as below:
<%= form_for(#entry) do |q| %>
NOTE:
The controller name is not as per Rails convention so it is messing up the params hash. Instead of getting entry as a key, you are getting entrie. I would recommend changing the controller name EntrysController to EntriesController. Renaming the file entrys_controller.rb to entries_controller.rb. Also, update the routes specific to this controller in routes.rb by replacing all occurrences of entrys with entries
I am a newbie to Ruby on Rails and have scoured Stackoverflow and the internet to the best of my abilities and am still stumped.
In my set-up, a Rating belongs_to a Product and has_many Comments. I'm using simple-form and trying to use nested fields_for to add RatingComment through the Rating form. Interestingly, when using the singular form of :rating_comment, the field is displayed. But as expected, I get the unpermitted parameter error when trying to save. When I use plural :rating_comments, the field disappears. This is similar to this SO posting, but adding #rating.rating_comments.build to new action still does not work for me. I've tried restarting the server many times, and even reset the database to no avail. Would appreciate any assistance as I've been struggling with this issue for the past few days.
Note: I've also taken out what I think is irrelevant code from the snippets below. If I need to show more information, please do let me know. Thanks in advance!
routes.rb
resources :ratings, only: [:new, :create, :edit, :update, :destroy] do
resources :rating_comments, shallow: true
end
rating.rb
class Rating < ActiveRecord::Base
belongs_to :product
belongs_to :user
has_many :rating_comments, foreign_key: "rating_id", dependent: :destroy
accepts_nested_attributes_for :rating_comments, reject_if: :all_blank
end
rating_comment.rb
class RatingComment < ActiveRecord::Base
belongs_to :rating
validates :rating_id, presence: true
end
ratings_controller.rb
class RatingsController < ApplicationController
before_action :signed_in_user, only: [:create, :new, :show]
def new
#product = Product.find(params[:id])
#rating = #product.ratings.new
#rating.rating_comments.build
end
def create
#product = Product.find(params[:product_id])
#rating = #product.ratings.build(rating_params)
#rating.user_id = current_user.id
...
private
def rating_params
params.require(:rating).permit(:user_id, :product_id, :rating, rating_comments_attributes: [:rating_id, :content])
end
end
ratings/_new_rating_form.html.erb
<%= simple_form_for([#product, #rating], html: { class: 'form-horizontal' }) do |f| %>
<%= f.error_notification %>
<%= f.input :rating, collection: 1..10, as: :radio_buttons,
item_wrapper_class: 'inline', checked: 5 %>
<%= f.simple_fields_for :rating_comments do |rc| %>
<fieldset>
<%= rc.input :content, label: "Comments" %>
</fieldset>
<% end %>
<%= f.error :base %>
<%= f.button :submit, "Submit" %>
<% end %>
Very embarrassed to admit that it turns out that I had the view written in the wrong action. Once I put it in the new.html, it finally worked.