I have two models
Article
class Article < ActiveRecord::Base
mount_uploader :photo, ImageUploader
has_many :comments
has_many :article_tags
has_many :tags, :through => :article_tags
belongs_to :category
validates :title, presence: true
validates :text, presence: true
end
ArticleTag
class ArticleTag < ActiveRecord::Base
belongs_to :article
belongs_to :tag
end
Tag
class Tag < ActiveRecord::Base
has_many :article_tags
has_many :articles, :through => :article_tags
end
This is how i am getting the tags in the .
@article = params[:article]
@tags = params[:tag_ids]
Now the real problem comes with posting the article into the articles table as well as the posting the tags associated with the various articles into the article_tags table.
Update
I am using simple_form_for gem which allows me to create a multi-select in bootstrap using the association method so the problem is not getting the tags into the form but rather posting them into the database(creating new rows for the article_tags). I want to be able to retrieve them via @article.article_tags. This is what is was trying but i don't know if it is right.
@article_params = params[:article]
article_params[:tag_ids].each do |tag|
@article_tag = @article.article_tags.build('article_id'=>@article.id,'tag_id'=>tag)
@article_tag.save
end
def article_params
params.require(:article).permit(:title,:category_id,:text, :photo,:tag_ids => [])
end
This has to be done as the article is being created it's like posting to two tables at the same time in the same method ie the articles and article_tags tables.