2016-11-22 40 views
0

我从一个在线教程构建应用程序。它跟踪“电影”和“出租”。我正在设法创建一个新的租赁部分。当我提交表单,我得到这个错误:Ruby on Rails的形成错误

ActiveModel::ForbiddenAttributesError in RentalsController#create 

以下是完整的租金控制器:

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(params[:rental]) 
    if @rental.save 
     redirect_to new_rental_path(:id => @movie.id) 
    end 
end 
end 

这似乎再跟这条线具体为:

 @rental = @movie.rentals.build(params[:rental]) 

这里是租赁模式:

class Rental < ApplicationRecord 
has_one :movie 
end 

这里是电影控制器:

class MoviesController < ApplicationController 

def new 
    @movie = Movie.new 
    @movies = Movie.all 
end 

def create 
    @movie = Movie.new(movie_params) 
    if @movie.save 
     redirect_to new_movie_path 
    end 
end 

private 

def movie_params 
    params.require(:movie).permit(:title, :year) 
end 
end 

这里是电影模式:

class Movie < ApplicationRecord 
has_many :rentals 
end 

这里是路线:

Rails.application.routes.draw do 
resources :movies, :rentals 
root 'movies#new' 

end 

这里是形式:

<h1><%= @movie.title %></h1> 

<%= form_for @rental, :url => {:action => :create, :id => @movie.id } do |r| %> 
Borrowed on: <%= r.text_field :borrowed_on %><br /> 
Returned on: <%= r.text_field :returned_on %><br /> 
<br /> 
<%= r.button :submit %> 
<% end %> 
<br /> 
<%= link_to "back", new_movie_path %> 

我不知道WH在继续。从我可以告诉我,我正在复制教程。任何帮助将非常感激!

+0

当您尝试发送您还没有加入到PARAMS方法的参数时,该错误会发生,在这种情况下,你缺少完全的rental_params方法。 –

回答

2

您没有使用强params用于在rentals,因此ActiveModel::ForbiddenAttributesError错误。


这应该修正这个错误:

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) 
    if @rental.save 
     redirect_to new_rental_path(:id => @movie.id) 
    end 
    end 

    private 

    def rental_params 
    params.require(:rental).permit(:borrowed_on, :rented_on) 
    end 
end 
+0

现在,我得到这个错误:“在分配属性,你必须通过一个哈希作为参数。”有什么想法吗? –

+0

'rental_params'看起来像什么?此外,发布错误 – Rashmirathi

+0

的一些stracktrace高清rental_params \t params.require(:租赁).permit(:borrowed_on,:rented_on) 结束 –