How to access the values of an associated model
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开发者_StackOverflow, 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 :post
in your Tag
class and has_many :tags
in your Post
class then the tags
attribute is a list so you either need to iterate over it:
post.tags.each {|tag| puts tag.politics}
Or index into it:
post.tags[0].politics
From an outside glance this type of model doesn't make too much sense though. Maybe do has_one :tag
in the Post
class instead. Then you can call post.tag.politics
.
精彩评论