Thursday, April 19, 2012

rails model association using has_many: through

i have a lessons table and a tags table. i associate both of the them using a has_many :through relationship and my middle table is tags_relationship.rb



class Lesson < ActiveRecord::Base
attr_accessible :title, :desc, :content, :tag_name
belongs_to :user

has_many :tag_relationships
has_many :tags, :through => :tag_relationships
end

class Tag < ActiveRecord::Base
attr_accessible :name

has_many :tag_relationships
has_many :lessons, :through => :tag_relationships
end


in one of my views, im trying to create a a virtual attribute. i have...



    <div class="tags">
<%= f.label :tag_name, "Tags" %>
<%= f.text_field :tag_name, data: { autocomplete_source: tags_path} %>
</div>


but my lessons table doesn't have that attribute, tag_name, so it calls my method instead



    def tag_name
????????
end

def tag_name=(name)
self.tag = Tag.find_or_initialize_by_name(name) if name.present?
end


however im not sure what to put inside the ????????. im trying to refer the :name attribute inside my tags table.



back then i used a has_many and belongs_to relationship. my lesson belonged to a tag (which was wrong) but i was able to write...



tag.name


and it worked. but since its a has_many :through now, im not sure. i tried using tags.name, Lessons.tags.name, etc but i cant seem to get it to work. how can i refer to the tags table name attribute? thank you





No comments:

Post a Comment