【问题标题】:Rails: "Couldn't find Movie with 'id'=" (ActiveRecord::RecordNotFound)Rails:“找不到带有'id'的电影=”(ActiveRecord::RecordNotFound)
【发布时间】:2015-01-29 15:08:48
【问题描述】:

我正在关注一个非常基本的应用程序的教程,所以这应该是一个简单的修复,但我无法弄清楚。它说它找不到'id = all'的电影

本教程有点过时,我已经不得不进行一些更改,例如 params.require,但仅此而已。

movie_controller.rb

class MoviesController < ApplicationController
  def new
    @movie = Movie.new
    @movies = Movie.find(:all)
  end

  def create
    @movie = Movie.new(params[:movie_id])
    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

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 %>

new.html.erb(用于出租)

Movie: <%= @movie.title %> <%= link_to "back", new_movie_path %>
<hr>

<%= form_for @rental do |f| %>
  Borrowed on: <%= f.text_field :borrowed_on %> <br>
  Returned on: <%= f.text_field :returned_on %> <br>
  <%= f.submit %>
<% end %>

我的路线只是resources :movies,以防万一。

【问题讨论】:

  • @movies = Movie.find(:all)这是错误的。应该只是@movies = Movie.all
  • 啊,这更有意义!除了现在当我填写电影标题,年份并按提交时,我得到的只是一个“(”,不管我输入了什么......你明白为什么吗?
  • 看来您正在学习一个相当古老的教程(可能适用于 Rails 2.x)。语法已经改变,旧的语法在 Rails 的最新版本中不再适用。你可能想看看教程:railstutorial.org/book
  • 那是因为你在这一行缺少)&lt;%= item.title %&gt; (&lt;%= item.year %&gt;

标签: ruby-on-rails ruby activerecord


【解决方案1】:

您需要这样做才能保存数据,在create 操作中,使用params[:movie_id] 代替comment_params

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

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    有一个建议,你可以改进格式,

    class MoviesController < ApplicationController
      def new
       @movie = Movie.new
       @movies = Movie.find(:all)
      end
    
      def create
       @movie = Movie.new(params[:movie_id])
       if @movie.save
         redirect_to new_movie_path
       end
      end
    
     def comment_params
       params.require(:movie).permit(:title, :year)
     end
    end
    

    在您的控制器新方法中,它应该类似于 @movies = Movie.all,Movie.find 基本上带有 ID,并且您有用于许可属性的 comment_params,但您没有通过在 create action 中,它应该像这样 Movie.new(comment_params) on create action,这是 rails 4 中的新安全功能

    【讨论】:

    • 确保 rails 控制台,当你调用 create 时,它​​都插入了你需要的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多