2016-11-22 39 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) 結束 –