2013-06-11 3 views
0

У меня здесь немного дилемма.Heroku + Rails Error ActiveRecord :: StatementInvalid

У меня есть комментарии леска и через Фильмы эшафот

При переходе на страницу фильма и создать новый комментарий, я иду здесь/кино/12/комментарии/новый (12 будучи ИО)

И сделал это мой контроллер

def new 
    @movie = Movie.find(params[:movie_id]) 
    @comment = @movie.comments.new 
    @search = Movie.search(params[:q]) 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @comment } 
    end 
    end 

Но когда я запустить в Heroku я получаю эту ошибку

*Processing by CommentsController#new as HTML 
ActiveRecord::StatementInvalid (PG::Error: ERROR: invalid input syntax for integer: "movie_id" 

Completed 500 Internal Server Error in 636ms 
LINE 1: ... "movies".* FROM "movies" WHERE "movies"."id" = 'movie_id'... 

Parameters: {"movie_id"=>"the-social-network"} 
app/controllers/comments_controller.rb:99:in `load_movie'* 

Я попытался удалить @movie = Movie.find(params[:movie_id]) или добавление .to_i в конце, как указано здесь Why does this :id in Rails not work with Postgresql but it does work with MySQL?, но до сих пор не повезло

Любые идеи? Спасибо!

comment_form (вид)

<%= simple_form_for(@comment) do |f| %> 
    <%= f.error_notification %> 

    <div class="form-inputs"> 
    <%= f.input :subject %> 
    <%= f.input :body %> 
    <%= f.input :movie_id %> 
    </div> 

    <div class="form-actions"> 
    <%= f.button :submit %> 
    </div> 
<% end %> 

Movie.rb

class Movie < ActiveRecord::Base 
    attr_accessible :title 


has_many :comments, :dependent => :destroy 

     extend FriendlyId 
    friendly_id :titleyear, use: :history 
    def titleyear 
    "#{title} #{id}" 
    end 

end 

Comment.rb

class Comment < ActiveRecord::Base 
    attr_accessible :body, :movie_id, :subject, :user_id 

    belongs_to :user 
    belongs_to :movie 




end 

Comments_controller.rb

class CommentsController < ApplicationController 
    # GET /comments 
    # GET /comments.json 
    before_filter :load_movie 
    before_filter :authenticate_user!, only: [:new,:create,:edit,:destroy] 



    def index 
    @comments = @movie.comments.all 
    @search = Movie.search(params[:q]) 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @comments } 
    end 
    end 

    # GET /comments/1 
    # GET /comments/1.json 
    def show 
    @comment = Comment.find(params[:id]) 
    @search = Movie.search(params[:q]) 

    respond_to do |format| 
     format.html # show.html.erb 
     format.json { render json: @comment } 
    end 
    end 

    # GET /comments/new 
    # GET /comments/new.json 
    def new 
    @movie = Movie.find(params[:movie_id]) 
    @comment = @movie.comments.new 
    @search = Movie.search(params[:q]) 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @comment } 
    end 
    end 

    # GET /comments/1/edit 
    def edit 
    @comment = Comment.find(params[:id]) 
    @search = Movie.search(params[:q]) 

    end 

    # POST /comments 
    # POST /comments.json 
    def create 
    @comment = Comment.new(params[:comment]) 
    @search = Movie.search(params[:q]) 

    respond_to do |format| 
     if @comment.save 
     format.html { redirect_to :back } 
     format.json { render json: @comment, status: :created, location: @comment } 
     else 
     format.html { render action: "new" } 
     format.json { render json: @comment.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PUT /comments/1 
    # PUT /comments/1.json 
    def update 
    @comment = Comment.find(params[:id]) 
    @search = Movie.search(params[:q]) 

    respond_to do |format| 
     if @comment.update_attributes(params[:comment]) 
     format.html { redirect_to (@movie), notice: 'Comment was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: "edit" } 
     format.json { render json: @comment.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /comments/1 
    # DELETE /comments/1.json 
    def destroy 
    @comment = Comment.find(params[:id]) 
    @comment.destroy 

    respond_to do |format| 
     format.html { redirect_to comments_url } 
     format.json { head :no_content } 
    end 
    end 

private 
    def load_movie 
     @movie = Movie.find_by_id(:movie_id) 
    end 


end 
+0

Похоже, что 'movie_id' на самом деле является« социальной сетью », которая не является целым числом. –

+0

Можете ли вы разместить свое мнение? Проблема более чем вероятна в вашей форме. – zeantsoi

+0

Ваше мнение выглядит правильно, но необычно, что ': movie_id' передает строку типа URL, а не целое число id. Можете ли вы опубликовать обе модели «Кино» и «Комментарий»? – zeantsoi

ответ

2

Параметр movie_id, поскольку вы передаете его, на самом деле не является id, но строка: Parameters: {"movie_id"=>"the-social-network"}.

На ваш взгляд, возможно, что-то неправильно настроено. Убедитесь, что вы передаете movie.id, а не что-то еще.

РЕДАКТИРОВАТЬ:

Ошибка принимается указывает, что строка the-social-network в настоящее время передается от сегмента movie_id URL. Вам нужно получить доступ к вашей форме, посетив путь, который проходит в числе в качестве второго параметра, например http://yoursite/movies/2/comments/new, а не http://yoursite/movies/the-social-network/comments/new.

+0

Итак, как бы я изменил movie_id, чтобы передать параметр? – PMP

+0

Хм ... можете ли вы зайти в консоль Rails и опубликовать пример существующего объекта «Комментарий»? Мне было бы интересно узнать, что такое атрибут 'movie_id'. Из командной строки введите 'rails console', затем' Comment.first'. Комментарий назад с тем, что он возвращает. – zeantsoi

+0

Комментировать Загрузить (0.8ms) SELECT «comments». * FROM «comments» LIMIT 1 => # <Комментарий id: 1, subject: "Test Comment", body: "Это тестовый комментарий, movie_id: 21, created_at : «2013-06-06 16:20:15», updated_at: «2013-06-06 16:20:47», user_id: nil> – PMP

Смежные вопросы