在Rails中给一条记录加上标签

问题描述 投票:0回答:1

我试图创建一个模型,在这个模型中,用户可以通过 rails 中的标记将一条记录附加到关联的记录上。然而,当我试图将一个标签添加到一个活动记录上时,这个标签只被添加到次要记录上。例如,如果我试图将Record 2标记到Record 1上,它就会将Record 2标记到Record 2上。我目前的代码如下。

RecordTagging模型

class Recordtagging < ApplicationRecord
  belongs_to :record
end

记录控制器

def record_params
        params.require(:record).permit(:name, :record_list, :record, { record_ids: [] }, :record_ids)
    end

记录模型

class Record < ApplicationRecord

    has_many :Recordtaggings
    has_many :records, through: :recordtaggings

    validates :name, presence: true
    validates :name, uniqueness: true

    def self.recordtagged_with(name)
        Record.find_by!(name: name).records
    end

    def self.record_counts
        Record.select('records.*, count(recordtaggings.record_id) as count').joins(:recordtaggings).group('recordtaggings.record_id')
    end

    def record_list
        record.map(&:name).join(', ')
    end

    def record_list=(names)
        self.records = names.split(',').map do |n|
            Record.where(name: n.strip).first_or_create!
        end
    end
end

記錄展示

<%= raw @record.records.map(&:name).map { |t| link_to t, records_path(t) }.join(', ') %>
ruby-on-rails model controller tagging
1个回答
0
投票

为了维护Record对象与另一个Record对象之间的关系,中间人RecordTagging必须有两个字段,指定第一个记录和第二个记录。这里你只在RecordTagging上指定了一个字段record_id,它可以给记录本身打标签。

你需要的是

class RecordTagging
   belongs_to record_1, class_name: 'Record', optional: true
   belongs_to record_2, class_name: 'Record', optional: true
end
© www.soinside.com 2019 - 2024. All rights reserved.