0

我在一个社交网站上工作(老实说,基本上是一个 facebook 的副本......),我重用了 insoshi 的大部分内容。但是 insoshi 的供稿对我的喜好不够准确。因为它不支持更专业的消息。您将在以下代码中看到我的意思:

item = activity.item
relationship = relationship(item)
case relationship
   when 1
     raw %(<p>You wrote on your own wall: <br/>
     #{truncate(item.body, :length => 20)}</p>)
   when 2
     raw %(<p>#{link_to item.user.name, item.user} wrote on your wall</p>)
   when 3
     raw %(<p>#{link_to item.user.name, item.user} wrote on his wall</p>)
   when 4
     raw %(<p>You wrote on #{link_to item.user.name, item.user}'s wall</p>)
   when 5
     raw %(<p>#{link_to item.user.name, item.user} wrote on 
              #{link_to item.contact.name, item.contact}'s wall</p>)
end

    def relationship(item) 
        unless item.owner.nil?
          contact = item.owner #so that it works for posts as well
        else
          contact = item.contact
        end
        user = item.user

        if current_user != contact or current_user != user
          return 5
        else
          if current_user == contact
            if current_user == user
              return 1
            else
              return 2
            end
          else
            if contact == user
              return 3
            else
              return 4
            end
          end
        end
end

我有不同类型的物品。通常项目有一个“用户”和一个“联系人”。除了帖子,它们还有一个“用户”和一个“所有者”。因为帖子的其他人可以将其写在某人的墙上(因此为所有者)。

现在,当我尝试将联系人设置为 item.contact 时,问题就出现了......它只是不断地用“NoMethod”错误来困扰我,说 item.contact 不存在。(如果该项目是帖子而不是“连接”或类似项目,则这一点很明显)。

所以我征求你的意见:1)用更多的红宝石解决问题,或者2)改变帖子模型,让帖子有一个“用户”和一个“联系人”?

谢谢大家斯特凡诺

4

2 回答 2

0

我会用 Ruby 代码修复。

contact = item.contact if item.respond_to? :contact

通过使用 response_to? 这适用于任何有联系的班级。

于 2010-09-17T12:04:41.797 回答
0

根据您的逻辑,关系 3 和 4 永远不会返回。我认为你在哪里拥有current_user != contact or current_user != user,你就应该拥有and。就个人而言,我总是使用 && 因为如果第一个条件为假,它会短路。但是,在我的重构中,您不需要它,因为如果没有其他情况匹配,它会返回 5。

我将关系逻辑移至 Item 模型并在帮助程序中进行了适当的更新。

查看助手:

case item.relationship_to_user(current_user)
when 1
  raw %(<p>You wrote on your own wall: <br/>
  #{truncate(item.body, :length => 20)}</p>)
when 2
  raw %(<p>#{link_to item.user.name, item.user} wrote on your wall</p>)
when 3
  raw %(<p>#{link_to item.user.name, item.user} wrote on his wall</p>)
when 4
  raw %(<p>You wrote on #{link_to item.user.name, item.user}'s wall</p>)
when 5
  raw %(<p>#{link_to item.user.name, item.user} wrote on 
  #{link_to item.contact.name, item.contact}'s wall</p>)
end

物品类别

class Item < ActiveRecord::Base

  def relationship_to_user(current_user)
    contact = owner || contact  

    return 1 if current_user == contact && current_user == user
    return 2 if current_user == contact
    return 3 if current_user != contact
    return 4 if current_user != contact && contact != user

    return 5
    # return 5 if current_user != contact or current_user != user
  end

end
于 2010-09-17T23:17:21.007 回答