New to Rails development. I'm creating an application that has users, artists and tags associated with artists applied by users. Here are the two models for artists and tags:
class Artist < ApplicationRecord
has_and_belongs_to_many :tags
end
class Tag < ApplicationRecord
has_and_belongs_to_many :artists
end
A user has the option to either create a new tag, in which case we create tag record in the tags table, and an association record between the newly created tag and the artist it was created for. The second option is clicking an existing tag for that artist, in this case I would like to increase the count in the association table for that tag for that artist, but Active Record doesn't index join tables so while I can create add a count column to the join table, I can't access and modify that column. But I can do this in SQL:
UPDATE Artists_Tags
SET count = count + 1
WHERE artist_id=artistid AND tag_id=tagid;
Table in 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
But I can't put this SQL query into my controller method to update count. Am I approaching this problem wrong? I'd appreciate any tips. Note: Increasing count is used to display the most applied tag to that artist.