I have Tag set up as a polymorphic model in my Rails 5.1.3 app. I'm trying to set a collection_select up so that I can choose tags from a dropdown.
The form creates new tags and the association works great, however, I cannot get the tag name passed into the form, so my tags are saving name as an empty string.
_form.html.erb
<%= form_for [taggable, Tag.new] do |f| %>
<%= f.collection_select :taggable_id, Tag.order(:name), :id, :name %>
<%= f.submit %>
<% end %>
tags_controller.rb
class TagsController < ApplicationController
before_action :authenticate_user!
def create
@tag = @taggable.tags.new(tag_params)
@tag.user_id = current_user.id
if @tag.save
redirect_to book_path(@taggable.book_id), notice: "Tag saved"
else
redirect_to root_path, notice: "Sorry, something went wrong"
end
end
private
def tag_params
params.require(:tag).permit(:name)
end
end
Tag params:
=> <ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"z2PLrvETqtq742zmr3pghEYYqoGoLv05gLP3OXopLM+blWWw+HmR4AMMDB+5ET3E5YLXeyhMCFMHfdxJNHlkZA==", "tag"=><ActionController::Parameters {"taggable_id"=>"1"} permitted: false>, "commit"=>"Create Tag", "controller"=>"books/tags", "action"=>"create", "book_id"=>"26"} permitted: false>
edit: adding models and fields
book.rb
class Book < ApplicationRecord
has_many :tags, as: :taggable
end
tag.rb
class Tag < ApplicationRecord
belongs_to :taggable, polymorphic: true
end
tags table
create_table "tags", force: :cascade do |t|
t.string "taggable_type"
t.integer "taggable_id"
t.integer "user_id"
t.text "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end