2015-03-31 102 views
0

我想通过索引页上的按钮从数据库检索特定记录,并将该对象存储在临时数组中,然后在特定视图中显示对象的属性。但是find方法的记录没有存储在一个变量中,我不知道为什么......我得到nil的错误:NilClass。(在我的项目中,我希望能够为一个有序病人列出一个天,并在视图中显示它们)从数据库到数组的记录

这是我的代码:

patient_index.html.erb(从支架)
<tbody> 
<% @patients.each do |patient| %> 
    <tr> 
    <td><%= patient.name %></td> 
    <td><%= patient.last_name %></td>   
    <td><%= patient.id %></td> 
    <td><%= link_to 'Show', patient %></td> 
    <td><%= link_to 'Edit', edit_patient_path(patient) %></td> 
    <td><%= link_to 'Destroy', patient, method: :delete, data: { confirm: 'Are you sure?' } %></td> 
    <td> <%= button_to 'Order', order_path(id: patient)%></td> 
    <th><%= @temp[0].name %></th> #testing if it shows the value here 
    </tr> 
<% end %> 

的routes.rb

post 'order', to: 'patients#order'

patients_controller.rb

def index 
    @patients = Patient.all 
    end 

    def show 
    end 

    def edit ... #generated by scaffold 

    def destroy ... 

    def update ... 

    def order 
    @temp = [] 
    @the_patient = Patient.find(params[:id]) 
    @temp << @the_patient 

    redirect_to patients_url 

    end 

错误图像链接http://imgur.com/nJdyR2E求助

感谢,并建议:)

+0

你在哪里定义'@ patients'?也请发布完整的错误信息与相关的回溯。 – shivam 2015-03-31 18:11:34

+0

抱怨说'@ patients'不再存在,因为你没有在'#order'中定义它。 – engineersmnky 2015-03-31 18:46:32

+0

当你重定向时,变量'@ temp'丢失,如果你愿意的话,将这段代码移动到索引动作 – 2015-04-01 18:10:54

回答

0

没有足够的信息来告诉,但(稍有不同..我得到了代码,并在我的语言变量名)是您也许做

redirect_to patients_url 

#order行动,但你的意思是:

​​

这将是您的#show操作。我知道你正在使用不同的语言。也许这个问题是一个复数错误?

如果不是,这是我的答案:

您正在尝试没有定义@temp建立一个索引页。想想看,你要求索引,所以它建立索引页面。当时什么是@temp?它不会被设置,直到你点击按钮,因为#index没有定义它。但即使在您将其定义在#order之后,您仍会重定向至#index,并将其重置为[]。您需要重构您的应用程序。一个简单的黑客就是重定向到一个新的页面,该页面有自己的代码,包括@temp,并且从#index中获取@temp

线沿线的:

patients_url -> index action -> patients_url with button press -> 
    order action -> order_display_url 
+0

试图在application_controller'@temp = []'全局定义'@ temp',然后在'#订单'控制器我试着只是简单地向该数组添加一个字符串'@temp <<“hello”'但我越来越错误:未定义的方法'<<'为零:NilClass所以我认为问题是在数组中的轨道或者其他东西 – misanek 2015-04-02 14:57:35

+0

这个问题很可能不是数组中的数组。仅仅因为你在这个层面上定义了一些东西,并不意味着它会起作用。 Rails约定配置。索引视图是索引视图。如果你想在点击按钮后添加一些东西给它,你需要使用AJAX,或者有一个不同的视图来获取Order动作的信息。你正试图让rails做一些它没有设计的事情。 – Beartech 2015-04-03 02:49:43

+0

感谢您的帮助;)我想出了不同的方式,通过添加属性排序患者数据库和按钮,我只是将属性设置为true,然后我只是使用'Patient.all.where(ordered:true)'来分配给一个变量 – misanek 2015-04-03 20:13:00