Ruby on rails 从关联模型回调访问所有模型
我有一个带有回调的问题模型:Ruby on rails 从关联模型回调访问所有模型,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我有一个带有回调的问题模型: class Question < ActiveRecord::Base has_many :qtags has_many :tags, through: :qtags after_save { self.tags.find_or_create(self) } end 这会将问题传递给标记,该标记将从标记列表中创建一些标记 在tag.rb中,我想访问所有标记,以检查是否已经存在一个标记: class Tag < ActiveRecord::
class Question < ActiveRecord::Base
has_many :qtags
has_many :tags, through: :qtags
after_save { self.tags.find_or_create(self) }
end
这会将问题传递给标记,该标记将从标记列表中创建一些标记
在tag.rb中,我想访问所有标记,以检查是否已经存在一个标记:
class Tag < ActiveRecord::Base
has_many :qtags
has_many :questions, through: :qtags
def self.find_or_create(question)
question.tags.destroy_all
question.tag_list.split(' ').each do |tag|
# Tag.where here can't access all the tags, just the associated ones.
if Tag.where(name: tag).exists? && question.tags.ids.exclude?(Tag.where(name: tag).first.id)
question.tags << Tag.where(name: tag)
elsif Tag.where(name: tag).blank?
question.tags << Tag.create(name: tag)
end
end
end
end
但是,这仅检查具有相关问题id的标记
因此,当我使用binding.pry添加pry控制台时:
5: def self.find_or_create(question)
6: question.tags.destroy_all
=> 7: binding.pry
8: question.tag_list.split(' ').each do |tag|
9: if Tag.where(name: tag).exists? && question.tags.ids.exclude?(Tag.where(name: tag).first.id)
10: question.tags << Tag.where(name: tag)
11: elsif Tag.where(name: tag).blank?
12: question.tags << Tag.create(name: tag)
13: end
14: end
15: end
[1] pry(Tag)> Tag.all
Tag Load (0.1ms) SELECT "tags".* FROM "tags" INNER JOIN "qtags" ON "tags"."id" = "qtags"."tag_id" WHERE "qtags"."question_id" = ? [["question_id", 11]]
它仅选择具有关联问题id的标记
如何使用Tag.all或Tag.where.访问所有标记。。不仅仅是哪一个有来电者问题id?我无法解决这个问题,但我是这样解决的:
def create
Tag.find_or_create(@question) if @question.save
respond_with(@question)
end
我没有使用回调,而是从控制器中调用find_或_create方法,如下所示:
def create
Tag.find_or_create(@question) if @question.save
respond_with(@question)
end
编辑:
现在我知道是什么错误了:
after_save { self.tags.find_or_create(self) }
这应该是:
after_save { Tag.find_or_create(self) }
tag_name是在哪里定义的?question.tag_列表被拆分为tag_name,但问题是,为什么tag.all被调用的问题id为:[question.id,11],为什么我不能访问所有标记?对不起,我不明白。您能在问题中添加更多代码吗?您已替换为的部件。。。例如。问题不清楚,请就此添加更多输入。问题调用Tag方法来创建标记,但该方法无法检查标记是否已存在,因为它只获取已关联的标记。