【问题标题】:Rails many-to-many assignment with unique DB entriesRails 具有唯一数据库条目的多对多分配
【发布时间】:2021-04-20 11:10:45
【问题描述】:

我正在运行带有 Ruby 2.6.7 的 Rails 5.2.1 应用程序。

我有一个类似论坛的应用程序,我正在尝试实现一个自制的标记系统,类似于 StackOverflow 的系统。我选择这样做的方式是有一个简单的连接表,它将促进我的TagQuestion 模型的has_many through: 关系。

我遇到的问题是我不确定如何在不在标签表中创建新条目的情况下将标签分配给问题(假设甚至可以这样做)。最好,我希望数据库对于每个唯一标签只有 1 个条目。

例如,当创建一个新问题时,用户会选择一个已经存在的标签,并且该问题将链接到相关标签的特定 ID。

  • 用户创建问题,使用id: 1,选择数据库中具有id: 1 的标签
  • 在 Join 表中,这看起来像 question_id: 1 | tag_id: 1
  • 用户创建另一个问题,现在使用id: 2,并再次选择标签id: 1
  • 那个表有question_id: 2 | tag_id: 1

就像现在一样,如果我执行question.tags.create(id: 1),则不会创建标签。另一方面,如果我执行question.tags.create(name: "tagname"),则确实会创建标签,但它是作为新标签条目创建的并且具有id: 2,从而留下两个同名标签。

我的模型:

class Question < ApplicationRecord
  has_many :question_tags, dependent: :destroy
  has_many :tags, through: :question_tags
end

class Tag < ApplicationRecord
  has_many :question_tags, dependent: :destroy
  has_many :questions, through: :question_tags
end

class QuestionTag < ApplicationRecord
  belongs_to :question
  belongs_to :tag
end

我怎样才能达到我想要的结果?据推测,我会使用某种before_Savebefore_create 钩子来为我处理它,但我不确定如何正确地实现它。

【问题讨论】:

    标签: ruby-on-rails postgresql many-to-many


    【解决方案1】:

    您可以从用户的选择中找到所有标签 ID,然后添加它们。 ActiveRecord 为您提供#tag_ids。在您的服务或控制器或 w/e 中,您可以将它们添加到那里;即选择问题的标签,从选择值中获取 id,在您的控制器中允许 tag_ids,然后根据需要进行分配。

    # form
    <%= select question[tag_ids][], .... %>
    
    # controller
    
    private
    
    def question_params
      params.require(:question).permit(:id, ..., tag_ids: [])
    end
    
    # Then used similarly whereever you choose
    question = Question.find(params[:id])
    question.tag_ids << question_params[:tag_ids]
    or
    question.tag_ids = question_params[:tag_ids]
    
    You can create/update a question with the tag_ids like any attribute
    

    【讨论】:

      猜你喜欢
      • 2012-04-24
      • 1970-01-01
      • 2011-12-19
      • 2012-01-09
      • 2019-08-20
      • 2018-05-04
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      相关资源
      最近更新 更多