仍然获得nil'不是ActiveModel兼容的对象,即使控制器应该重定向

时间:2013-12-17 09:26:17

标签: ruby-on-rails

在common_apps / show中,我写了一个if / else语句来检查用户是否有'common_app',如果没有,我会重定向它们。

在相应的common_apps / show视图中,我只渲染common_app。

但是,在应该重定向用户的情况下,rails正在产生错误

nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.

发生这种情况的原因是因为@common_app将为nil,如果用户没有common_app。但是,在common_app控制器中我确实有if / else语句,所以如果common_app为nil,那么它应该重定向到另一个页面。

我该怎么写这个,以便在用户没有common_app的情况下重定向,而不是看到nil错误?

这是我在控制器中的节目定义:

  def show
    if current_user.common_app.present?
      redirect_to new_common_app, notice: "Looks like you haven't made your common application. Fill it in below."
    else
      @common_app = current_user.common_app
    end
  end

这是我的节目观点:

<% provide(:title, current_user.name) %>
<h1><%= current_user.name %></h1>

<ul>
    <%= render @common_app %>
</ul>

3 个答案:

答案 0 :(得分:1)

你对if条件的逻辑是错误的。可以写得更好:

def show
  @common_app = current_user.common_app
  redirect_to new_common_app_path, notice: "Looks like you haven't made your common application. Fill it in below." unless @common_app.present?
end    

答案 1 :(得分:1)

在您的show动作中为什么不更改为if current_user.common_app.nil?或者甚至!current_user.common_app

答案 2 :(得分:1)

如果您想在部分

中使用@common_app变量,可以这样做
<%= render partial: "name_of_partial", locals: {common_app: @common_app} %>