I have the code
def showTags(post)
tagString = ''
tagString += "Politics " if post.tags(:politics)
tagString += "Technology " if post.tags(:technology)
tagString += "Entertainment " if post.tags(:entertainment)
tagString += "Sports " if post.tags(:sports)
tagString += "Science " if post.tags(:science)
tagString += "Crime " if post.tags(:crime)
tagString += "Business " if post.tags(:business)
tagString += "Social " if post.tags(:social)
tagString += "Nature " if post.tags(:nature)
tagString += "Other " if post.tags(:other)
return tagString
end
My tags model has 10 boolean values (politics, tech, etc…) and belongs_to :post. When you make a new post there are check boxes that correspond to each field. So after making a post there are some trues and some false values. The problem arises when I call this method in the post#index, in order to display which tags belong to this post. The problem is that all of the words display, i played with the console and the post.tags is correct (some true and some false values) however if post.tags(:politics) (or whatever) always returns true. I tried using if post.tags.politics but that just gave an error.
Can someone please help me with this.
Assuming you have
belongs_to :postin yourTagclass andhas_many :tagsin yourPostclass then thetagsattribute is a list so you either need to iterate over it:Or index into it:
From an outside glance this type of model doesn’t make too much sense though. Maybe do
has_one :tagin thePostclass instead. Then you can callpost.tag.politics.