ruby on rails - one-to-many through referance table -
i'm trying understand how implement one-to-many relationship through reference table. i'm looking on this guide though write on 1 model has_many one-to-many i'm not sure (i wrote it's not working). anyway i'm doing save me table, , doing right , not working.
the model following:
microposts, :id, :content
tag, :id, :name tag_microposts, :tag_id, :micropost_id article, :id, :text article_microposts, :article_id, :micropost_id i can 2 microposts tables id of tag/article. think doing better , righter.
in end what's interesting me microposts through tag model. in tag_controller able do: 
def index   @tag = tag.find(params[:id])   @microposts = @tag.microposts end some code:
class tag < activerecord::base   ...    has_many :tag_microposts, foreign_key: :tag_id, dependent: :destroy   has_many :microposts, through: :tag_microposts, source: :micropost    ... end   class tagmicropost < activerecord::base   validates :tag_id, presence: true   validates :micropost_id, presence: true end   class micropost < activerecord::base   belongs_to :user   belongs_to :tag    validates :content, presence: true, length: {minimum: 10, maximum: 250}   validates :user_id, presence: true end 
may ask why using reference table this? can one-to-many association 2 models associating. if want associate tag many posts can in models.
class tag < activerecord::base has_many :microposts end  class micropost < activerecord::base belongs_to :tag #added in edit belongs_to :article  validates :content, presence: true, length: {minimum: 10, maximum: 250} validates :user_id, presence: true end this should let do:
@tag.microposts just fine. forgien key stored in micro post model sure add column. can use active migration that. call column tag_id, rails should take care of rest.
edit*
a added article association. problem raised relevant if need article/tag given micropost. code still pretty simple model.
@tag ||= @micropost.tag using conditional assignment operator assign @tag if association there. if give me more specifics how these models used can give better answer.
Comments
Post a Comment