0

Using rails 4 I have a class Userbookrank where a user ranks a book in a library and the table includes user_id, book_id, and rank. The userbookranks_controller.rb is the following:

class UserbookranksController < ApplicationController
  def new
    @book = Book.find(params[:book_id])
    @user = User.find(params[:user_id])
    @userbookrank = Userbookrank.new
  end

  def create
    @userbookrank = Userbookrank.new(userbookrank_params)
    if @userbookrank.save
      redirect_to userbookrank_path(@userbookrank)
    else
      redirect_to :root
    end
  end

  def show
    @userbookrank = Userbookrank.find(params[:id])
  end

  private
  def userbookrank_params
    params.require(:userbookrank).permit(:user_id, :book_id, :rank)
  end
end

and the new.html.erb file is the following:

Rank a book

<p> Book title: %=@book.title % </p>
<p> Book author: %=@book.author.name % </p>
<%=form_for :userbookrank do |f| %>
  <%=f.hidden_field :book_id, :value => @book.id%>
  <%=f.hidden_field :user_id, :value => current_user.id%>
  <p> 
    <%=f.label :rank %>
    <br>
    <%=f.number_field :rank %>
  </p>
  <p>     
    <%=f.submit "Rank book"%>
  </p>
<% end %>

the show.html.erb file is the following: The book you ranked is...

<p>Title: <%=@userbookrank.book.title %> </p>  
<p>Author: <%=@userbookrank.book.author.name %> </p>   
<p>Rank: <%=@userbookrank.rank %> </p>    
<p> <%=link_to 'Back to the book menu', userbookranks_path %> </p>

the routes file includes the following:

resources :userbookranks

and when I submit a rank there is a routing error: No route matches [POST] "/userbookranks/new"

the rake routes includes the following:

userbookranks_path  GET     /userbookranks(.:format)    userbookranks#index
    POST    /userbookranks(.:format)    userbookranks#create
new_userbookrank_path   GET     /userbookranks/new(.:format)    userbookranks#new
edit_userbookrank_path  GET     /userbookranks/:id/edit(.:format)   userbookranks#edit
userbookrank_path   GET     /userbookranks/:id(.:format)    userbookranks#show
    PATCH   /userbookranks/:id(.:format)    userbookranks#update
    PUT     /userbookranks/:id(.:format)    userbookranks#update
    DELETE  /userbookranks/:id(.:format)    userbookranks#destroy 

Thank you very much in advance.

usha
  • 27,505
  • 5
  • 67
  • 87

2 Answers2

2

In your new.html.haml, use @userbookrank object that you initialize in your new action.

<p> Book title: %=@book.title % </p>
<p> Book author: %=@book.author.name % </p>
<%=form_for @userbookrank do |f| %>
  <%=f.hidden_field :book_id, :value => @book.id%>
  <%=f.hidden_field :user_id, :value => current_user.id%>
  <p> 
    <%=f.label :rank %>
    <br>
    <%=f.number_field :rank %>
  </p>
  <p>     
    <%=f.submit "Rank book"%>
  </p>
<% end %>
usha
  • 27,505
  • 5
  • 67
  • 87
0

you should change new.html.erb to

<%=form_for @userbookrank do |f| %>
munya
  • 71
  • 2