无法在Rails 3上的render partial中访问模型属性

时间:2013-09-13 03:58:01

标签: ruby-on-rails ruby-on-rails-3 renderpartial

js.erb

$('#search_div').html('<%=j render :partial=> 'find_book',locals: { book: @results }, :formats => :html  %>')

html.erb

<% @book=book %>
<%= @book.inspect %>
<% @book.id %>

当我检查时,它会找到并告诉我

[#<Book id: 55, name: "consequatur laborum quidem excepturi", isbn: 9782943127358, price: 4023, comment: nil, created_at: "2013-09-01 02:59:29", updated_at: "2013-09-01 02:59:29", author: nil, sale_type: nil, publisher: nil, sn: nil, category: nil>] [#<Book id: 55, name: "consequatur laborum quidem excepturi", isbn: 9782943127358, price: 4023, comment: nil, created_at: "2013-09-01 02:59:29", updated_at: "2013-09-01 02:59:29", author: nil, sale_type: nil, publisher: nil, sn: nil, category: nil>]

但是当我尝试使用@ book.id

时 它给了我。

ActionView::Template::Error (undefined method `id' for #<Array:0x007faef875b260>):
    1: <% @book=book %>
    2: <%= @book.inspect %>
    3: <% @book.id %>

2 个答案:

答案 0 :(得分:0)

没有id,因为对象book是一个数组,而不是一个书对象。查看检查周围的[]

要读取每本书的属性,您需要循环使用此局部变量。

首先对代码进行了一些改进

  1. 使用books代替book作为变量名。

  2. 当局部变量可用时,避免使用实例变量。

  3. 然后是代码

    # JS
    $('#search_div').html('<%=j render :partial=> 'find_book',
                                       locals: { books: @results } %>'
    
    # partial: _find_book.html.erb
    <% books.each do |book| %>
       <%= book.id %>
       <%= book.other_attribute %>
    <% end %>
    

答案 1 :(得分:0)

如您所见,您的@book是一个数组:

[#<Book id: 55, name: "consequatur laborum quidem excepturi", isbn: 9782943127358, price: 4023, comment: nil, created_at: "2013-09-01 02:59:29", updated_at: "2013-09-01 02:59:29", author: nil, sale_type: nil, publisher: nil, sn: nil, category: nil>] [#<Book id: 55, name: "consequatur laborum quidem excepturi", isbn: 9782943127358, price: 4023, comment: nil, created_at: "2013-09-01 02:59:29", updated_at: "2013-09-01 02:59:29", author: nil, sale_type: nil, publisher: nil, sn: nil, category: nil>]

注意开头和结尾的“方括号”([])。并且错误显示您无法在数组上调用id,或者

@book.first.id etc 

或在传递时传递第一个结果,如:

$('#search_div').html('<%=j render :partial=> 'find_book',locals: { book: @results.first }, :formats => :html  %>')

或者,如果你的计划是拥有多个对象,那么循环通过变量@book来显示所有细节。

相关问题