我有Tag
在我的Rails 5.1.3應用程序中設置爲多態模型。我試圖設置一個collection_select
,以便我可以從下拉列表中選擇標籤。collection_select爲多態模型
表單創建新標籤並且關聯工作得很好,但是,我無法將標籤名稱傳遞到表單中,因此我的標籤將name
保存爲空字符串。
_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
末
標籤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>
編輯:增加車型和字段
book.rb
class Book < ApplicationRecord
has_many :tags, as: :taggable
end
tag.rb
class Tag < ApplicationRecord
belongs_to :taggable, polymorphic: true
end
標籤表
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
請在模型中添加模型和字段? – Ankit
@Ankit完成.... – BillyBib