简体   繁体   English

每个循环的Ruby Rails form_for

[英]Ruby Rails form_for for each loop

any idea why this loop not working? 知道为什么这个循环不起作用?

<% @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 %>

on user controller: 在用户控制器上:

@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])

but when I use find(:first or find(:last it shows (but repeating the value) when it is :all it throws this error: 但是当我使用find(:firstfind(:last它显示(但重复值)时:它会抛出此错误:

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

Thanks! 谢谢! im newb to ruby :D 我对红宝石的新闻:D

Your user should look like this -- > 您的用户应该看起来像这样 - >

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

Your view should look like this --> 您的视图应该如下所示 - >

<% @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 %>

Hi Johnny, the issue is with the instance variables we have in the controller --> 嗨Johnny,问题在于我们在控制器中的实例变量 - >

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

From what I understand, User has_many books. 根据我的理解,用户有很多书。

In this case @book isn't actually one instance of a book, but it's just the same as @books . 在这种情况下, @book实际上并不是一本书的一个实例,但它和@books Similarly, @bookedit is getting all Books with an Id, but it's not passing the id of the user. 同样, @bookedit正在获取带有Id的所有Books,但它没有传递用户的id。

Because of the association between users and books, you can get all the books I user has by 由于用户和书籍之间的关联,您可以获得我用户拥有的所有书籍

@books = @user.books

In your view, If we do 在您看来,如果我们这样做

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

We iterate through all the books, and run a form_for that book 我们遍历所有书籍,并为该书运行form_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM