简体   繁体   中英

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:

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

Thanks! im newb to ruby :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 -->

@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 . Similarly, @bookedit is getting all Books with an Id, but it's not passing the id of the user.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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