Rails应用评论未保存到数据库

时间:2016-09-27 18:48:38

标签: ruby-on-rails

我正在从在线教程构建书评应用程序。我想用表格保存书评。我有一张书桌和一张评论表。如果图书评论保存,我已将评论表单重定向到图书展示页面。如果没有,请渲染新的'再次。当我尝试保存时,我得到零错误。它只是让我回到新的评论页面。我进入了控制台,评论没有保存。我不知道发生了什么。有人可以帮忙吗?

这是我的图书管理员:

class BooksController < ApplicationController
before_action :authenticate_user!, only: [:new, :edit, :index, :show] 


def index
    @books = Book.all
end

def new
    @book = current_user.books.new
end

def create 
    @book = current_user.books.build(book_params)
    if @book.save 
        redirect_to books_path
    else
        render 'new'
    end
end

def show
    @book = Book.find(params[:id])
end 

def edit 
    @book = Book.find(params[:id])
end

def update
@book = Book.find(params[:id])
if @book.update(book_params)
    redirect_to book_path(@book)
else
    render "edit"
end
end 


def destroy
    @book = Book.find(params[:id])
    @book.destroy
    if @book.destroy 
        redirect_to books_path
    else
        render 'show_books_path'
    end
end

private
    def book_params
        params.require(:book).permit(:title, :description, :author, :category_id, :book_img)
    end
end

这是我的评论控制器:

class ReviewsController < ApplicationController
before_action :find_book


def new 
    @review = Review.new
end


def create
    @review = Review.new(review_params)
    @review.book_id = @book.id
    @review.user_id = current_user.id
    if @review.save
        redirect_to book_path(@book)
    else
        render 'new'
    end
end



def edit

end

def update

end

def destroy

end

private

    def review_params 
        params.require(:review).permit(:rating, :comment)
    end

    def find_book
        @book = Book.find(params[:book_id])
    end
end

以下是我的评论模型:

class Review < ApplicationRecord

belongs_to :books
belongs_to :users

end

这是我的书模型:

class Book < ApplicationRecord

belongs_to :user
has_many :reviews

has_attached_file :book_img, styles: { book_index: "250x350>", book_show:    "400x600>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :book_img, content_type: /\Aimage\/.*\z/
end

我正在使用设计表格。这就是我所拥有的:

<%= simple_form_for([@book, @book.reviews.build]) do |f| %>
 <p>Rating</p>
 <%= f.input :rating, label: false, :class => "input" %>
 <p>Comment</p>
 <%= f.text_area :comment, label: false, :class => "input" %>
 <%= f.button :submit, :class => "submit" %>
<% end %> 

这是我的路线档案:

Rails.application.routes.draw do


devise_for :users

resources :books do 
    resources :reviews
end

root "books#index"

end

我真的不确定这里发生了什么。当我进入控制台时,评论没有被保存。最终,我想展示它们,但我还没有完成这一步。任何帮助将非常感谢!

1 个答案:

答案 0 :(得分:1)

我在你的Review模型中看到了这一点:

class Review < ApplicationRecord

  belongs_to :books
  belongs_to :users

end

什么时候应该是这样的:

class Review < ApplicationRecord

  belongs_to :book
  belongs_to :user

end

belongs_to个关联必须使用单数术语