I have three models, Artwork, ArtworkTag, and Tag, where ArtworkTag represents an m:n relation between Artwork and Tag. Tag only stores the tag name, i.e. :tag.
When creating tags from ArtworkTagsController, it’s necessary to first see if the :tag exists in the tags table, create it if not, and then use the tag id to make the relation in ArtworkTag.
Below you can see that I’m calling Tag directly from this controller, which I don’t think is the right practice.
How should I be handling this situation with the proper separation of concerns?
def create
tag = params[:artwork_tag][:tag].downcase
@tag = Tag.find_by_tag(tag)
if @tag.blank?
@tag = Tag.new(:tag => tag)
@tag.save
end
artwork_id = params[:artwork_tag][:artwork_id]
user_id = params[:artwork_tag][:user_id]
artwork_tag = {
"tag_id" => @tag.id,
"artwork_id" => artwork_id,
"user_id" => user_id
}
@artwork_tag = ArtworkTag.new(:tag_id => @tag.id, :artwork_id => artwork_id, :user_id => user_id)
@artwork_tag.save
respond_to do |format|
format.json { render :json => {
"id" => @artwork_tag.id, "tag" => @tag.tag, "artwork_id" => artwork_id },
:status => :created }
end
end
I would do something like this: