【问题标题】:How do i get regular expressions to work in this rails app?我如何让正则表达式在这个 Rails 应用程序中工作?
【发布时间】:2013-10-22 02:55:15
【问题描述】:

我是 Rails 和正则表达式的新手。我正在尝试制作一个应用程序,用户可以使用以下两种电子邮件地址之一进行注册:user@a.edu 或 user@b.edu。我正在制作一个页面,显示所有不是当前用户类型的用户。例如,jason@a.edu 已登录,页面将显示所有类型 b 的用户。如果 lauren@b.edu 已登录,该页面将显示所有类型 a 的用户。我正在尝试使用正则表达式根据电子邮件地址了解登录的用户类型,并在用户单击链接时动态生成页面。我在模型中创建了这个方法:

def other_schools
   if /.+@a\.edu/.match(current_user.email)
      User.where(email != /.+@a\.edu/)
   else
      render :text => 'NOT WORKING', :status => :unauthorized
   end
end

这里是控制器:

def index
    #authorize! :index, :static_pages 
    @users = current_user.other_schools
end

这是显示每个用户的视图:

<% @users.each do |user| %>
          <li class="span3">
                <div class="thumbnail" style="background: white;">
                  <%= image_tag "idea.jpeg" %>
                  <h3><%= user.role %></h3>
                  <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
                  <a class="btn btn-primary">View</a>
                </div>
          </li>
<% end %>

视图只是循环通过@user 对象。当我尝试加载页面时,我被告知有一个未定义的局部变量或方法“current_user”。我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails regex roles


    【解决方案1】:

    您的模型不“知道” helpers 方法。 Current_user 就是其中之一。所以你需要将用户对象传递给函数/使用当前用户实例来获取结果:

    # controller
    def index
        #authorize! :index, :static_pages
        @users = User.other_schools(current_user)
    end
    
    # User model
    def self.other_schools(user) # class method
       if user.email.match(/.+@a\.edu/)
          User.where("email NOT LIKE '%@a.edu'")
       else
          User.where('false') # workaround to returns an empty AR::Relation
       end
    end
    

    替代方案(使用 current_user 实例):

    # controller
    def index
        #authorize! :index, :static_pages
        @users = current_user.other_schools
        if @users.blank?
            render :text => 'NOT WORKING', :status => :unauthorized
        end
    end
    
    # User model
    def other_schools # instance method
       if self.email.match(/.+@a\.edu/)
          User.where("email NOT LIKE '%@a.edu'")
       else
          User.where('false') # workaround to returns an empty AR::Relation
       end
    end
    

    【讨论】:

    • 谢谢。我尝试实现替代版本,但现在它说视图中有一个未定义的方法“每个”。这对我来说毫无意义。我进行了编辑并将视图放入上面的问题内容中。
    • 我刚刚更新了我的答案@Philip7899 问题是您尝试在模型中进行渲染,但应该在控制器中完成
    • 谢谢。现在它正在渲染“不工作”,但它实际上应该工作。我认为这与我的正则表达式有关。你知道我的正则表达式是否正确吗?
    • 不,这不正确,对于 PG SQL,您需要使用以下语法:.where("email =~ ?", /.+@a\.edu/) --- 你的 DBMS 是什么? MySQL?后GreSQL? MongoDB?
    • 我想说的是电子邮件不相等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多