[英]Can't figure out how to add polymorphic tags in a rails app
我有一个带有用户列表的示例Rails应用程序。 我想尝试使用多态标记。
目前,我可以通过控制台通过以下方式为用户创建标签User.first.tags.create(name: "new tag name")
但是在通过Webform添加它们时遇到问题
这是我所做的:
rails g model Tag name taggable:references{polymorphic}
产生了以下迁移
class CreateTags < ActiveRecord::Migration[5.1]
def change
create_table :tags do |t|
t.string :name
t.references :taggable, polymorphic: true
t.timestamps
end
end
end
标签模型
class Tag < ApplicationRecord
belongs_to :taggable, polymorphic: true
end
用户模型
class User < ApplicationRecord
has_many :tags, as: :taggable
end
标签字段
<%= form_with(model: user, local: true) do |form| %>
...
<div class="field">
<%= form.label :tag_list %>
<%= form.text_field :tag_list, placeholder: "tags separated by comma" %>
</div>
...
<% end %>
我还找到了以下代码,但是You cannot call create unless the parent is saved
。
在用户模型中添加了以下设置器,并在用户的强大参数中添加了:tag_list
def tag_list=(vals)
self.tags = vals.split(", ").each do |val|
tags.where(name: val.strip).first_or_create!
end
end
您可以使用嵌套形式添加标签
用户模型
class User < ApplicationRecord
has_many :tags, as: :taggable
accepts_nested_attributes_for :tags
end
以你的形式
<%= form_with(model: user, local: true) do |form| %>
...
<div class="field">
<% form.fields_for :tags do |t| %>
<%= u.text_field :tag_name %>
<% end %>
</div>
...
<% end %>
在您的控制器中,请同时添加其他属性
params.require(:user).permit( tags_attributes: [:id,:tag_name])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.