使用rails 4我有一个Userbookrank类,用户在一个库中对一本书进行排名,该表包含user_id,book_id和rank。 userbookranks_controller.rb如下:
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
和new.html.erb
文件如下:
排名
<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 %>
show.html.erb
文件如下:
你排名的那本书是......
<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>
路线文件包括以下内容:
resources :userbookranks
当我提交排名时,会出现路由错误:No route matches [POST] "/userbookranks/new"
rake路线包括以下内容:
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
非常感谢你。
答案 0 :(得分:2)
在new.html.haml
中,使用您在新操作中初始化的@userbookrank
对象。
<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 %>
答案 1 :(得分:0)
您应该将new.html.erb更改为
<%=form_for @userbookrank do |f| %>