Rails 5 permit strong params select box

Rails 5 permit strong params select box

Rails 5 permit strong params select box


Rails 5 permit strong params select box issues with unpermitted params


app/models/Post
class Post < ApplicationRecord
 has_and_belongs_to_many :tags
 accepts_nested_attributes_for :tags
end

class Brand < ApplicationRecord
 has_and_belongs_to_many :posts
end

app/controllers/posts_controller

def post_params
 params.require(:post).permit(:title,:body,tag_ids:[])
end

app/views/posts/_form.html.erb
form_for @post do 
 f.select :tag_ids, Tag.all.collect {|tag| [tag.name,tag.id]}, {include_blank: true}, {class: "some-class"}
  
end


this will raise unpermitted params :tag_ids issue and selected tag to post will not saved

To solve this issue u can change permit_params like this

def post_params
 params.require(:post).permit(:title,:body,:tag_ids,tag_ids: [])
end

tag_ids: [] must be last one in permit params its important, we added :tag_ids and it solve issue


this solution allow you select only one tag for post


there are another solution if you want select many tags to one post in form

to this option you can save params without changes like this


app/controllers/posts_controller
def post_params
 params.require(:post).permit(:title,:body,tag_ids:[])
end


but change you form like this


app/views/posts/_form.html.erb
form_for @post do 
 f.select :tag_ids, Tag.all.collect {|tag| [tag.name,tag.id]}, {include_blank: true}, { multiple: true,
class: "some-class"}

we added multiple: true option to form_for select

now you cant select many tags for one post and save post


That is it, happy coding


Feel free to join us

t.me/bravowebdevchannel

t.me/bravowebdev




Report Page