无法弄清楚如何在rails应用程序中添加多态标签

时间:2022-07-16 03:58:53

I have a sample rails app with a list of users. And I wanted to experiment with polymorphic tags.

我有一个带有用户列表的示例rails应用程序。我想尝试使用多态标签。

At this moment I can create tags for users through console in the following way User.first.tags.create(name: "new tag name")

此时我可以通过以下方式通过控制台为用户创建标签User.first.tags.create(name:“new tag name”)

But have problems with adding them through webform

但是通过webform添加它们有问题

Here's what I did:

这是我做的:

rails g model Tag name taggable:references{polymorphic}

generated the following migration

生成以下迁移

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

tag model

标签模型

class Tag < ApplicationRecord
  belongs_to :taggable, polymorphic: true
end

user model

用户模型

class User < ApplicationRecord
  has_many :tags, as: :taggable
end

Tags field

标签字段

<%= 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 %>

I also found the following code but getting You cannot call create unless the parent is saved error.

我还发现了以下代码,但是除非父节点错误,否则无法调用create。

added the following setter to user model and added :tag_list to strong params of user

将以下setter添加到用户模型,并将tag_list添加到用户的强params

  def tag_list=(vals)
    self.tags = vals.split(", ").each do |val|
      tags.where(name: val.strip).first_or_create!
    end
  end

1 个解决方案

#1


1  

You can add tags with nested form

您可以使用嵌套表单添加标签

user model

用户模型

class User < ApplicationRecord
  has_many :tags, as: :taggable
  accepts_nested_attributes_for :tags 
end

in your form

在你的形式

<%= 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 %>

in your controller , please add other attribute as well

在您的控制器中,请添加其他属性

params.require(:user).permit( tags_attributes: [:id,:tag_name])

#1


1  

You can add tags with nested form

您可以使用嵌套表单添加标签

user model

用户模型

class User < ApplicationRecord
  has_many :tags, as: :taggable
  accepts_nested_attributes_for :tags 
end

in your form

在你的形式

<%= 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 %>

in your controller , please add other attribute as well

在您的控制器中,请添加其他属性

params.require(:user).permit( tags_attributes: [:id,:tag_name])