我建立一个基本的应用实践中,你输入一个电影,当它被租了。 此举形式做工精细,电影链接到租赁日期的标题。 但租金的形式似乎并没有工作。 我没有得到一个错误或任何东西,它只是不保存。 我假设的问题是我创造的方法,但我无法弄清楚。
movies_controller.rb
class MoviesController < ApplicationController
def new
@movie = Movie.new
@movies = Movie.all
end
def create
@movie = Movie.new(comment_params)
if @movie.save
redirect_to new_movie_path
end
end
def comment_params
params.require(:movie).permit(:title, :year)
end
end
rentals_controller.rb
class RentalsController < ApplicationController
def new
@movie = Movie.find(params[:id])
@rental = @movie.rentals.build
end
def create
@movie = Movie.find(params[:id])
@rental = @movie.rentals.build(rental_params[:rental_id])
if @rental.save
redirect_to new_rental_path(:id => @movie.id)
end
end
def rental_params
params.require(:rental).permit(:borrowed_on, :returned_on, :movie_id)
end
end
new.html.erb(租金)
Movie: <%= @movie.title %> <%= link_to "back", new_movie_path %>
<hr>
<%= form_for @rental, :url => { :action => :create, :id => @movie.id } do |f| %>
Borrowed on: <%= f.text_field :borrowed_on %> <br>
Returned on: <%= f.text_field :returned_on %> <br>
<%= f.submit %>
<% end %>
<hr>
Rentals:
<% if !@movie.rentals.blank? %>
<% for item in @movie.rentals %>
<%= item.borrowed_on %>, <%= item.returned_on %> <br>
<% end %>
<% else %>
No rentals yet
<% end %>
new.html.erb(动画)
Enter new movie information <br>
<%= form_for @movie do |f| %>
Title: <%= f.text_field :title %> <br>
Year: <%= f.text_field :year %> <br>
<%= f.submit %>
<% end %>
<hr>
List of all movies: <br>
<% if !@movies.blank? %>
<table border=1>
<tr>
<th> Title </th>
<th> Year </th>
</tr>
<% for item in @movies %>
<tr>
<td> <%= link_to item.title, :controller => :rentals, :action => :new, :id => item.id %> </td>
<td> <%= item.year %> </td>
</tr>
<% end %>
</table
<% end %>
路线:
Rails.application.routes.draw do
resources :movies do
resources :rentals
end
root 'movies#new'
end
耙路线:
Prefix Verb URI Pattern Controller#Action
movie_rentals GET /movies/:movie_id/rentals(.:format) rentals#index
POST /movies/:movie_id/rentals(.:format) rentals#create
new_movie_rental GET /movies/:movie_id/rentals/new(.:format) rentals#new
edit_movie_rental GET /movies/:movie_id/rentals/:id/edit(.:format) rentals#edit
movie_rental GET /movies/:movie_id/rentals/:id(.:format) rentals#show
PATCH /movies/:movie_id/rentals/:id(.:format) rentals#update
PUT /movies/:movie_id/rentals/:id(.:format) rentals#update
DELETE /movies/:movie_id/rentals/:id(.:format) rentals#destroy
movies GET /movies(.:format) movies#index
POST /movies(.:format) movies#create
new_movie GET /movies/new(.:format) movies#new
edit_movie GET /movies/:id/edit(.:format) movies#edit
movie GET /movies/:id(.:format) movies#show
PATCH /movies/:id(.:format) movies#update
PUT /movies/:id(.:format) movies#update
DELETE /movies/:id(.:format) movies#destroy
root GET / movies#new