I have a form that has some prebuilt tags that the user can select on a post. These tags are set up with a has_many through: relationship. Everything seems to be working but when I save (the post does save) there is an Unpermitted parameter: :tags from the controller's save method.
Tag model:
class Tag < ApplicationRecord
has_many :post_tags
has_many :posts, through: :post_tags
end
PostTag model:
class PostTag < ApplicationRecord
belongs_to :tag
belongs_to :post
end
Post model:
class Post < ApplicationRecord
...
has_many :post_tags
has_many :tags, through: :post_tags
Post controller methods:
def update
# saves tags
save_tags(#post, params[:post][:tags])
# updates params (not sure if this is required but I thought that updating the tags might be causing problems for the save.
params[:post][:tags] = #post.tags
if #post.update(post_params)
...
end
end
...
private
def post_params
params.require(:post).permit(:name, :notes, tags: [])
end
def save_tags(post, tags)
tags.each do |tag|
# tag.to_i, is because the form loads tags as just the tag id.
post.post_tags.build(tag: Tag.find_by(id: tag.to_i))
end
end
View (tags are checkboxes displayed as buttons):
<%= form.label :tags %>
<div class="box">
<% #tags.each do |tag| %>
<div class="check-btn">
<label>
<%= check_box_tag('dinner[tags][]', tag.id) %><span> <%= tag.name %></span>
</label>
</div>
<% end %>
</div>
Again this saves, and works fine, but I'd like to get rid of the Unpermitted parameter that is thrown in the console.
Your whole solution is creative but extremely redundant. Instead use the collection helpers:
<%= form_with(model: #post) |f| %>
<%= f.collection_check_boxes :tag_ids, Tag.all, :id, :name %>
<% end %>
tags_ids= is a special setter created by has_many :tags, through: :post_tags (they are created for all has_many and HABTM assocations). It takes an array of ids and will automatically create/delete join rows for you.
All you have to do in your controller is whitelist post[tag_ids] as an array:
class PostsController < ApplicationController
# ...
def create
#post = Post.new(post_params)
if #post.save
redirect_to #post
else
render :new
end
end
def update
if #post.update(post_params)
redirect_to #post
else
render :edit
end
end
private
# ...
def post_params
params.require(:post)
.permit(:name, :notes, tag_ids: [])
end
end
Related
Trying to save nested records through many-to-many association in Rails 6, but getting "tag must exist" error. Tag is a parent to post_tags which is the cross reference table between Posts and Tags (many-to-many). What I want to do is, when a new post is created, save post_tag records related to the selected tags on the post form. I looked at some related posts: here and here, and tried using inverse_of, autosave: true, and optional: true, but those don't seem to be working.
Here's what I have:
Models
class Post < ApplicationRecord
has_many :post_tags, dependent: :destroy, inverse_of: :post, autosave: true
has_many :tags, through: :post_tags
end
class PostTag < ApplicationRecord
belongs_to :post
belongs_to :tag
end
class Tag < ApplicationRecord
has_many :post_tags, dependent: :destroy, inverse_of: :tag, autosave: true
has_many :posts, through: :post_tags
end
Contoller
PostsController < ApplicationController
def new
#post = Post.new
#tags= Tag.all
#post.post_tags.build
end
def create
#post = Post.new(post_params)
#post.post_tags.build
if #post.save
...
end
end
private
def post_params
params.require(:post).permit(:title, :content, :user_id, post_tags_attributes: [tag_id: []])
end
end
Form
<%= f.fields_for :post_tags do |builder| %>
<%= builder.collection_check_boxes :tag_id, Tag.top_used, :id, :name, include_hidden: false %>
<% end %>
Error
(0.4ms) ROLLBACK
↳ app/controllers/posts_controller.rb:229:in `create'
Completed 422 Unprocessable Entity in 41ms (ActiveRecord: 3.7ms | Allocations: 15178)
ActiveRecord::RecordInvalid (Validation failed: Post tags tag must exist):
You don't need to explitly create the "join model" instances. You just need to pass an array to the tag_ids= setter created by has_many :tags, through: :post_tags.
<%= form_with(model: #post) %>
...
<div class="field">
<%= f.label :tag_ids %>
<%= f.collection_check_boxes :tag_ids, #tags, :id, :name %>
</div>
...
<% end %>
Your controller should look like:
PostsController < ApplicationController
def new
#post = Post.new
#tags = Tag.all
end
def create
#post = Post.new(post_params)
if #post.save
redirect_to #post, status: :created
else
#tags = Tag.all
render :new
end
end
private
def post_params
params.require(:post)
.permit(:title, :content, :user_id, tag_ids: [])
end
end
Using nested attributes and fields_for to create the join model instances is really only needed if you need to store additional information in the join model.
any help would be most appreciated, I am rather new to Rails.
I have two models a Shopping List and a Product. I'd like to save/update multiple products to a shopping list at a time.
The suggested changes are not updating the models. I've been googling and is "attr_accessor" or find_or_create_by the answer(s)?
Attempt 1 - Existing code
Error
> unknown attribute 'products_attributes' for Product.
Request
Parameters:
{"_method"=>"patch",
"authenticity_token"=>"3BgTQth38d5ykd3EHiuV1hkUqBZaTmedaJai3p9AR1N2bPlHraVANaxxe5lQYaVcWNoydA3Hb3ooMZxx15YnOQ==",
"list"=>
{"products_attributes"=>
{"0"=>{"title"=>"ten", "id"=>"12"},
"1"=>{"title"=>"two", "id"=>"13"},
"2"=>{"title"=>"three", "id"=>"14"},
"3"=>{"title"=>"four", "id"=>"15"},
"4"=>{"title"=>"five", "id"=>"16"},
"5"=>{"title"=>""},
"6"=>{"title"=>""},
"7"=>{"title"=>""},
"8"=>{"title"=>""},
"9"=>{"title"=>""},
"10"=>{"title"=>""}}},
"commit"=>"Save Products",
"id"=>"7"}
Attempt 2 - no errors the page reloads and none of the expected fields are updated. In earnest, I am Googling around and copying and pasting code snippets in the vain hope of unlocking the right combo.
Added to Products mode
class Product < ApplicationRecord
attr_accessor :products_attributes
belongs_to :list, optional: true
end
<%= content_tag(:h1, 'Add Products To This List') %>
<%= form_for(#list) do |f| %>
<%= f.fields_for :products do |pf| %>
<%= pf.text_field :title %><br>
<% end %>
<p>
<%= submit_tag "Save Products" %>
</p>
<% end %>
<%= link_to "Back To List", lists_path %>
list controller
def update
#render plain: params[:list].inspect
#list = List.find(params[:id])
if #list.products.update(params.require(:list).permit(:id, products_attributes: [:id, :title]))
redirect_to list_path(#list)
else
render 'show'
end
list model
class List < ApplicationRecord
has_many :products
accepts_nested_attributes_for :products
end
original do nothing - product model
class Product < ApplicationRecord
belongs_to :list, optional: true
end
If you just want a user to be able to select products and place them on a list you want a many to many association:
class List < ApplicationRecord
has_many :list_items
has_many :products, through: :list_products
end
class ListItem < ApplicationRecord
belongs_to :list
belongs_to :product
end
class Product < ApplicationRecord
has_many :list_items
has_many :lists, through: :list_products
end
This avoids creating vast numbers of duplicates on the products table and is known as normalization.
You can then select existing products by simply using a select:
<%= form_for(#list) do |f| %>
<%= f.label :product_ids %>
<%= f.collection_select(:product_ids, Product.all, :name, :id) %>
# ...
<% end %>
Note that this has nothing to with nested routes or nested attributes. Its just a select that uses the product_ids setter that's created by the association. This form will still submit to /lists or /lists/:id
You can whitelist an array of ids by:
def list_params
params.require(:list)
.permit(:foo, :bar, product_ids: [])
end
To add create/update/delete a bunch of nested records in one form you can use accepts_nested_attributes_for together with fields_for:
class List < ApplicationRecord
has_many :list_items
has_many :products, through: :list_products
accepts_nested_attributes_for :products
end
<%= form_for(#list) do |f| %>
<%= form.fields_for :products do |pf| %>
<%= pf.label :title %><br>
<%= pf.text_field :title %>
<% end %>
# ...
<% end %>
Of course fields_for won't show anything if you don't seed the association with records. That's where that loop that you completely misplaced comes in.
class ListsController < ApplicationController
# ...
def new
#list = List.new
5.times { #list.products.new } # seeds the form
end
def edit
#list = List.find(params[:id])
5.times { #list.products.new } # seeds the form
end
# ...
def update
#list = List.find(params[:id])
if #list.update(list_params)
redirect_to #list
else
render :new
end
end
private
def list_params
params.require(:list)
.permit(
:foo, :bar,
product_ids: [],
products_attrbutes: [ :title ]
)
end
end
Required reading:
Rails Guides: Nested forms
ActiveRecord::NestedAttributes
fields_for
Hi I'm having trouble by making the update and destroy method in my posts_controller, I'm able to create new Posts but I'm not able to update and I want to know how to destroy the model while destroying all the associations with the other model it.
My models:
Post Model
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
has_many :has_categories
has_many :categories, through: :has_categories
validates :title, presence: true,
length: { minimum: 5 }
after_create :save_categories
def categories=(value)
#categories = value
end
private
def save_categories
#categories.each do |category_id|
HasCategory.create(category_id: category_id, post_id: self.id)
end
end
end
Has_Category model
class HasCategory < ApplicationRecord
belongs_to :post
belongs_to :category
end
Category Model
class Category < ApplicationRecord
validates :name, presence: true
has_many :has_categories
has_many :posts, through: :has_categories
end
So in my partial form for the new and the edit actions is like this
<%= form_with model: #post, local: true do |form| %>
<!--Inputs before the categories-->
<div>
<label>Categories</label>
<% #categories.each do |category| %>
<div>
<%= check_box_tag "categories[]", category.id %> <%= category.name %>
</div>
<% end %>
</div>
<div>
<%= form.submit %>
</div>
<% end %>
My posts_controller create and update method
def create
#post = Post.new(post_params)
#post.categories = params[:categories]
if #post.save
redirect_to #post
else
render :new
end
end
def update
#post = Post.find(params[:id])
#post.categories = params[:categories]
if #post.update(post_params)
redirect_to #post
else
render :edit
end
end
My create action is working but the update action is just updating the inputs before the check_box_tag.
I know that the save_categories method on my Post model is the one who is taking the array I'm receiving from the form and creating the HasCategory association, How should I make the update action or even the destroy action given the situation that Is a many to many association?
The line has_many :categories, through: :has_categories gives you category_ids for post. So you can change your form:
<%= form_with model: #post, local: true do |form| %>
<!--Inputs before the categories-->
<div>
<label>Categories</label>
<%= f.collection_check_boxes(:category_ids, #categories, :id, :name)
</div>
<div>
<%= form.submit %>
</div>
<% end %>
and controller:
def create
# you need it here for correct rerendering `new` on validation error
#categories = Category.all # or maybe you have here more complicated query
#post = Post.new(post_params)
if #post.save
redirect_to #post
else
render :new
end
end
def update
# you need it here for correct rerendering `edit` on validation error
#categories = Category.all # or maybe you have here more complicated query
#post = Post.find(params[:id])
if #post.update(post_params)
redirect_to #post
else
render :edit
end
end
private
def post_params
params.require(:post).permit(:name, :some_other_post_params, category_ids: [])
end
You need to remove callback and categories=(value) method from the Post model. And define #categories in the new and edit actions. If it equals Category.all you can just put it to the form: f.collection_check_boxes(:category_ids, Category.all, :id, :name), without defining #variable
I'm trying to create a view allowing me to create and edit values of my joining table directly. This model is called 'hires'. I need to be able to create multiple rows in my joining table for when a child hires up to 2 books. I'm having some trouble and I suspect it's down to my associations...
I have 3 models. Each Child can have 2 books:
class Child < ActiveRecord::Base
has_many :hires
has_many :books, through: :hires
end
class Hire < ActiveRecord::Base
belongs_to :book
belongs_to :child
accepts_nested_attributes_for :book
accepts_nested_attributes_for :child
end
class Book < ActiveRecord::Base
has_many :hires
has_many :children, through: :hires
belongs_to :genres
end
The controller looks like this:
class HiresController < ApplicationController
...
def new
#hire = Hire.new
2.times do
#hire.build_book
end
end
def create
#hire = Hire.new(hire_params)
respond_to do |format|
if #hire.save
format.html { redirect_to #hire, notice: 'Hire was successfully created.' }
format.json { render :show, status: :created, location: #hire }
else
format.html { render :new }
format.json { render json: #hire.errors, status: :unprocessable_entity }
end
end
end
...
private
# Use callbacks to share common setup or constraints between actions.
def set_hire
#hire = Hire.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def hire_params
params.require(:hire).permit(:child_id, book_attributes: [ :id, :book_id, :_destroy])
end
end
The view likes this:
<%= form_for(#hire) do |f| %>
<%= f.label :child_id %><br>
<%= f.select(:child_id, Child.all.collect {|a| [a.nickname, a.id]}) -%>
<%= f.fields_for :books do |books_form| %>
<%= books_form.label :book_id %><br>
<%= books_form.select(:book_id, Book.all.collect {|a| [a.Title, a.id]}) %>
<%# books_form.text_field :book_id #%>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
The problem is, the hash is not submitting books_attributes as you'd expect, it's just submitting 'books':
Processing by HiresController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xx", "hire"=>{"child_id"=>"1", "books"=>{"book_id"=>"1"}}, "commit"=>"Create Hire"}
Unpermitted parameter: books
I suspect this is because my associations for the Hire model are:
belongs_to :book
accepts_nested_attributes_for :book
which means I can't build the attributes correctly but I'm not sure how to solve this. Any help would be great, am I solving this problem badly?
Try changing books_attributes to book_attributes in strong paramters for hire_param.
def hire_params
params.require(:hire).permit(:child_id, book_attributes: [ :id, :book_id, :_destroy])
end
I have a model (User) that has_many of another model (Profession) - and this is supposed to be represented by one (or multiple) select menu in a form.
I cannot get my head around why the select menu doesn't get rendered? Am I constructing the select helper in the wrong way? Or is something else wrong in the view or the controller? The name attribute of the User is showing up alright in the form.
The models:
class User < ActiveRecord::Base
has_many :occupations, dependent: :destroy
has_many :professions, through: :occupations
accepts_nested_attributes_for :occupations
end
class Profession < ActiveRecord::Base
has_many :occupations, dependent: :destroy
has_many :users, through: :occupations
end
class Occupation < ActiveRecord::Base
belongs_to :user
belongs_to :profession
end
The controller:
def edit
end
def create
#user = User.new(user_params)
if #user.save
redirect_to #user, notice: 'User was successfully created.'
else
render action: 'new'
end
end
private
def set_user
#user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name, :email, ocuppations_attributes: [:id, :user_id, :profession_id])
end
The view (compressed):
<%= form_for(#user) do |f| %>
<%= f.text_field :name %>
<%= f.fields_for :occupations do |builder| %>
<%= builder.select :profession_id, Profession.all.collect {|x| [x.title, x.id]} %>
<% end %>
<% end %>
Shouldn't that be a collection select?
<%= builder.collection_select(:profession_id, Profession.all, :id, :title) %>