【问题标题】:How to access the values of an associated model如何访问关联模型的值
【发布时间】:2011-07-14 03:58:02
【问题描述】:

我有密码

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

我的标签模型有 10 个布尔值(政治、技术等)和 belongs_to :post。当您发布新帖子时,会有对应于每个字段的复选框。因此,在发布帖子后,会有一些正确和错误的值。当我在 post#index 中调用此方法以显示哪些标签属于该帖子时,就会出现问题。问题是所有的单词都显示出来了,我用控制台玩了,post.tags 是正确的(一些是真值和一些假值)但是if post.tags(:politics)(或其他)总是返回真。我尝试使用if post.tags.politics,但这只是报错。

谁能帮帮我。

【问题讨论】:

    标签: ruby-on-rails post tags


    【解决方案1】:

    假设您的Tag 类中有belongs_to :postPost 类中有has_many :tags,那么tags 属性是一个列表,因此您需要对其进行迭代:

    post.tags.each {|tag| puts tag.politics}
    

    或索引到它:

    post.tags[0].politics
    

    从外观上看,这种类型的模型并没有太大意义。也许在Post 类中做has_one :tag。然后你可以拨打post.tag.politics

    【讨论】:

    • 嗯,我得到这个错误 can't convert Symbol into Integer 当我将它们切换到方括号时
    • 我更新了答案,但我不得不做出假设,因为你的模型不清楚。
    • 谢谢,但我认为使用 gem act-as-taggable-on 是可行的方法。或者也许只是将所有布尔值放在帖子表中,而不是使用单独的表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2014-04-27
    • 1970-01-01
    相关资源
    最近更新 更多