增加连接表中关联发生的次数

时间:2018-05-09 17:56:26

标签: sql ruby-on-rails activerecord associations

Rails开发的新手。我正在创建一个应用程序,其中包含与用户应用的艺术家相关联的用户,艺术家和标签。以下是艺术家和标签的两个模型:

class Artist < ApplicationRecord
  has_and_belongs_to_many :tags
end
class Tag < ApplicationRecord
  has_and_belongs_to_many :artists
end

用户可以选择创建新标记,在这种情况下,我们在标记表中创建标记记录,以及新创建的标记与为其创建的艺术家之间的关联记录。第二个选项是单击该艺术家的现有标签,在这种情况下,我想增加该艺术家的该标签的关联表中的计数,但Active Record不会索引连接表,因此我可以创建添加计数列到连接表,我无法访问和修改该列。但我可以在SQL中执行此操作:

UPDATE Artists_Tags
    SET count = count + 1
    WHERE artist_id=artistid AND tag_id=tagid;

schema.rb中的表:

create_table "artists_tags", id: false, force: :cascade do |t|
  t.bigint "artist_id", null: false
  t.bigint "tag_id", null: false
  t.integer "count", default: 1, null: false
  t.index ["artist_id", "tag_id"], name: 
"index_artists_tags_on_artist_id_and_tag_id"
end

但是我不能把这个SQL查询放到我的控制器方法中来更新计数。我接近这个问题了吗?我很感激任何提示。 注意:增加计数用于向该艺术家显示应用最多的标签。

1 个答案:

答案 0 :(得分:2)

我想问题是您正在使用HABTM关联,在这种情况下,您无法获得有关该关系的任何其他信息(请参阅http://blog.flatironschool.com/why-you-dont-need-has-and-belongs-to-many/中的详细信息)。我会改变使用has_many :through和新模型ArtistTag进行多对多关系的方式。会是这样的:

rails g model ArtistTag artist:references tag:references tag_count:integer

并将模型更改为:

class Artist < ApplicationRecord
  has_many :artist_tags
  has_many :tags, through: :artist_tags
end

class Tag < ApplicationRecord
  has_many :artist_tags
  has_many :artists, through: :artist_tags
end

就像那样,你可以做一些事情(使用主动记录):

artist_tag = artist.artist_tags.find_by_tag_id(your_tag_id)
artist_tag.update(tag_count: artist_tag.tag_count + 1)

我个人认为这是一种更好的方法,可以解决您的问题。希望这有帮助,祝你好运!

相关问题