2014-08-27 89 views
2

我是Rails的新手。我正在使用Rails 4,但我无法找到它们如何执行此操作或调用它。在Rails 4中创建当前变量

我有这个想法从devise在那里你可以在你的application.html.erb文件中使用devise和实施这样的事情:

<% if user_signed_in? %> 
     Logged in as <strong><%= current_user.email %></strong>. 

哪里user是色器件模型。 但是,当我尝试搜索user_signed_incurrent_user变量时,我根本找不到它!

所以基本上我想要做的是与我创建了名为profile另一个模型链接此user模型(这是用于devise)。这些模型通过它们的id链接,如果用户没有创建配置文件,则只需要求用户创建他/她的配置文件。 要做到这一点,我写这application.html.erb

<% if user_signed_in? && (current_profile.id != current_user.id)? %> 
    <%= link_to 'You have not created your profile! Please create your profile first.', update_profile_index_path, :class => 'navbar-link' %> 
<% else %> 
    <%= yield %> 
<% end %> 

如预期,因为我还没有定义current_profile不工作。我正的错误是:

undefined local variable or method `current_profile' for #<#<Class:0x000000044d6c60>:0x00000005d64110> 

我的问题是,如何创建一个名为current_profile变量,将包含当前配置文件,如current_user就是图谋呢?

+0

你为什么不干脆使用current_user.profile? – Rafal 2014-08-27 13:21:11

+0

current_user是一个设计模型。它没有配置文件? – 2014-08-27 13:21:38

+0

如果你在用户模型上定义了has_one配置文件,那么current_user.profile将起作用 – Rafal 2014-08-27 13:22:09

回答

3

通常的设置是添加一个带有user_id:整数字段的Profile模型。

定义的用户模型的协会[

has_one :profile 

然后你就可以直接使用

current_user.profile 
3

访问它可以做到以下几点:

class User 
    has_one :profile 
    # ... 

class Profile 
    belongs_to :user 
    # ... 

module ApplicationHelper # app/helpers/application_helper.rb 
    def current_profile 
    @current_profile ||= current_user.try(:profile) 
    @current_profile 
    end 
    # ... 

# view 
<% if user_signed_in? && current_profile.blank? %> 
    <%= link_to 'You have not created your profile! Please create your profile first.', update_profile_index_path, :class => 'navbar-link' %> 
<% else %> 
    <%= yield %> 
<% end %> 
+0

我在配置文件中has_one以及因为我想要严格,一个配置文件只有一个用户? – 2014-08-27 13:34:41

+0

@SarpKaya请参阅[在belongs_to'和'has_one'之间选择](http://guides.rubyonrails.org/association_basics。HTML#选择之间属于并且有一个) – Stefan 2014-08-27 13:38:25

+0

它的工作就像一个魅力!而这种事情就是我第一次想要的东西! – 2014-08-27 13:39:00