簡體   English   中英

每個循環的Ruby Rails form_for

[英]Ruby Rails form_for for each loop

知道為什么這個循環不起作用?

<% @books.each do |book| %>
    <%= form_for(@bookedit) do |f| %>
      <div class="field">
        <%= f.label :count, 'how many?' %><br />
        <%= f.number_field :count %>
      </div>
    <% end %>
<% end %>

在用戶控制器上:

@books = Book.where(user_id: current_user.id)
@book = Book.where(user_id: current_user.id)
@bookedit = Book.find(:all, :conditions => {:id => @book})

@user = User.find(params[:id])

但是當我使用find(:firstfind(:last它顯示(但重復值)時:它會拋出此錯誤:

NoMethodError in Users#account 
undefined method `book_book_path' for #<#<Class:0x6ec5650>:0x6ec3448>

謝謝! 我對紅寶石的新聞:D

您的用戶應該看起來像這樣 - >

@user = User.find(params[:id])
#or @user = current_user
@books = @user.books

您的視圖應該如下所示 - >

<% @books.each do |book| %>
    <%= form_for(book) do |f| %>
      <div class="field">
        <%= f.label :count, 'how many?' %><br />
        <%= f.number_field :count %>
      </div>
    <% end %>
<% end %>

嗨Johnny,問題在於我們在控制器中的實例變量 - >

@books = Book.where(user_id: current_user.id)
@book = Book.where(user_id: current_user.id)
@bookedit = Book.find(:all, :conditions => {:id => @book})

根據我的理解,用戶有很多書。

在這種情況下, @book實際上並不是一本書的一個實例,但它和@books 同樣, @bookedit正在獲取帶有Id的所有Books,但它沒有傳遞用戶的id。

由於用戶和書籍之間的關聯,您可以獲得我用戶擁有的所有書籍

@books = @user.books

在您看來,如果我們這樣做

<% @books.each do |book| %>
    <%= form_for(book) do |f| %>

我們遍歷所有書籍,並為該書運行form_

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM