2013-02-12 56 views
0

我正在研究微型社交网络,我有两种不同的帐户类型,用户可以是简介或页面。修改关系协会

class User < ActiveRecord::Base 

    has_one :profile 
    has_one :page 

end 

现在,当我想显示用户名,我做current_user.profile.name,但如果用户是“页”,我得到一个错误,很明显。

所以,我想这个

private 
    def current_user 
    if session[:user_id] 
     @current_user = User.find(session[:user_id]) 

     if @current_user.account_type == 'profile' 
     @current_user.profile = @current_user.page 
     end 

    end 
    end 

但它不工作。

任何帮助都很赞赏。非常感谢!

+0

这是一个有点混乱 - 如果帐户类型是一个配置文件,你为什么会设置自己作为一个页面?另外,我不确定'@ current_user.profile = @ current_user.page'会做什么,但'@ current_user.profile'将外键存储到'profile',所以你需要存储'如果你真的想这样做的话。 – TheDude 2013-02-12 23:16:32

+0

我试图删除current_user的“profile”var,并且他没有,并将配置文件设置为页面。所以我不必在每个视图中的current_user.profile和current_user.page之间进行更改。相反,我只是使用current_user.profile为 – 2013-02-12 23:19:03

回答

0

我真的不知道你在问什么,但你可以添加一个方法来User模型来处理这个问题:

class User < ActiveRecord::Base 

    has_one :profile 
    has_one :page 

    def name 
    if self.account_type == 'profile' 
     return self.profile.name 

    return <whatever for page> 
    end 
end 

编辑:

对于多个领域,为什么不使用为User方法:

class User < ActiveRecord::Base 

    # other code removed 

    def get_info(method, *args) 
     if self.account_type == 'profile' 
      return self.profile.send(method, *args) 
     end 
     self.page.send(method, *args) 
    end 
end 

因此,要利用这一点,说我们有a = User.find(:id)与任何id。然后,你可以做,假设aaccount_typeprofile

a.get_info(:name) # => a.profile.name

+0

是的,事情是我有很多字段,例如,配置文件有名称,年龄,性别等等。然后,页面有名称,说明,地址,国家等 – 2013-02-12 23:16:24

+0

如果你想这样做,我增加了更多。 – TheDude 2013-02-12 23:24:23

+0

是的,但现在我做了current_user.name并没有得到任何东西,或者我用错了吗?这是我第一次看到method_missing – 2013-02-12 23:25:09