nil类的未定义方法 - 从视图向控制器发送实例

时间:2014-05-01 22:17:41

标签: ruby-on-rails ruby-on-rails-4

我无法从视图中向控制器发送模型实例。

我有一个名为profile的模型和一个名为report的模型。

      <%= form_for(@reported, url: report_path(@profile), html: {method: "post"})  do |f| %>
          <button class="btn btn-default btn-xs disconnect" type="button" onclick="showReport();">
            <i class="fa fa-ban"></i> Report
          </button>
          <%= text_area :reason, :class => "form-control", :rows => "3", :placeholder => "Reason" %>
          <button class="btn btn-default btn-xs disconnect" type="submit" >
             Submit
          </button>
        <% end %>
      <% end %>

控制器 - 路线到这里

def report 
  @profile.whatever # error here! the @profile variable is nil! 
  #when I thought I passed it here.
end

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

为了使@profile在控制器中具有值,您必须对其进行初始化。通常,这是通过从数据库中提取值来完成的。

在您的控制器方法(report)中,您有一个包含URL或POST参数的params哈希,可能您想要的是params[:id]。因此,您应该像这样初始化您的对象:

@profile = Profile.find(params[:id])