아주 이상한 레일 동작을 디버깅하는 데 한 시간을 보냈습니다. 감안할 때 :Rails 모델에서 HABTM 동작을 '포함'하는 이유는 무엇입니까?
응용 프로그램/모델/user.rb
class User < ApplicationRecord
...
has_many :images
has_many :videos
...
has_many :tags
...
end
응용 프로그램/모델/image.rb
class Image < ApplicationRecord
...
belongs_to :user
...
has_and_belongs_to_many :tags
...
include TagsFunctions
...
end
응용 프로그램/모델/video.rb
class Video < ApplicationRecord
...
include TagsFunctions
...
belongs_to :user
...
has_and_belongs_to_many :tags
...
end
app/models 나는 그런 코드를 실행하면 /tag.rb
class Tag < ApplicationRecord
belongs_to :user
validates :text, uniqueness: {scope: :user}, presence: true
before_create :set_code
def set_code
return if self[:code].present?
loop do
self[:code] = [*'A'..'Z'].sample(8).join
break if Tag.find_by(code: self[:code]).nil?
end
end
end
응용 프로그램/모델/문제/tags_functions.rb는
module TagsFunctions
extend ActiveSupport::Concern
# hack for new models
included do
attr_accessor :tags_after_creation
after_create -> { self.tags_string = tags_after_creation if tags_after_creation.present? }
end
def tags_string
tags.pluck(:text).join(',')
end
def tags_string=(value)
unless user
@tags_after_creation = value
return
end
@tags_after_creation = ''
self.tags = []
value.to_s.split(',').map(&:strip).each do |tag_text|
tag = user.tags.find_or_create_by(text: tag_text)
self.tags << tag
end
end
end
:
user = User.first
tags_string = 'test'
image = user.images.create(tags_string: tags_string)
video = user.videos.create(tags_string: tags_string)
그것은 1 개 항목을 줄 것이다 image.tags
, 그러나 중복 항목 2 개는 video.tags
그러나 :
user = User.first
tags_string = 'test'
image = Image.create(user: user, tags_string: tags_string)
video = Video.create(user: user, tags_string: tags_string)
모든, 이미지에 대한 1 개 태그 및 비디오 더
그리고 ... 1 개 태그를 잘 작동을 우리는 include TagsFunctions
아래로 이동하는 경우has_and_belongs_to_many :tags
, video.rb
파일에서 두 코드 예제 모두 정상적으로 작동합니다.
나는 레일을 잘 알고 있다고 생각했지만,이 행동은 나에게 정말로 불분명하다.
레일 버전 : 5.1.1
나는 편집 한 질문과 tag.rb 내용을 추가했습니다. 저에게 이상한 점은 이미지와 비디오에서 두 줄이 동일하다는 것입니다. 내 응용 프로그램을 디버깅 할 때 habtm 연관이 두 곳에서 두 번 추가되고있는 것으로 나타났습니다. 첫 번째 레코드는'self.tags << tag' 라인이 실행될 때 추가되고 비디오 레코드가 저장 될 때 두번째 레코드가 추가 될 때 추가됩니다. –
내 영어로 죄송합니다 :) 말하기로 _ 태그 기능에서 사용자와 태그 연결을 연관시키는 것을 피할 수 있습니다 ._ 내가 has_many : 태그의 이름을 다른 것으로 변경해야한다는 것을 의미합니까? –