我有以下关联和相关控制器,在我的表单中,我添加了每个字段。但是当我尝试创建一个项目时,我仍然得到一个错误评级项目不能为空。我正在使用Rails 4.0。我确实为此进行了广泛的搜索,但仍然找不到我做错了什么。谢谢!
class Item < ActiveRecord::Base
has_many :ratings, dependent: :destroy
accepts_nested_attributes_for :ratings, :allow_destroy => true
validates :name , :length => { minimum: 3 }
validates :category , :length => { minimum: 3 }
end
class Ratings < ActiveRecord::Base
belongs_to :user
belongs_to :item
default_scope -> { order('created_at DESC') }
validates :user_id, :presence => true
validates :item_id, :presence => true
validates_numericality_of :rating, :greater_than_or_equal_to => 0
validates_numericality_of :rating, :less_than_or_equal_to => 5
end
class ItemsController < ApplicationController
before_action :set_item, only: [:show]
before_action :user_signed_in?, only: :create
def create
@item = Item.new
@rating = @item.ratings.build
@rating.comment = params[:item][:ratings_attributes][:comment]
@rating.rating = params[:item][:ratings_attributes][:rating]
@rating.user_id = current_user.id
@item.name = params[:item][:name]
@item.url = params[:item][:url]
@item.full_address = params[:item][:full_address]
@item.city = params[:item][:city]
@item.country = params[:item][:country]
@item.category = params[:item][:category]
respond_to do |format|
if @item.save
#TODO create rating here (First rating of an Item)
flash[:success] = "Welcome to inmyopnion"
format.html { redirect_to @item, notice: 'Item was successfully created.' }
format.json { render action: 'show', status: :created, location: @item }
else
format.html { render action: 'new' }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
def new
@item = Item.new
end
def show
end
def destroy
end
private
def set_item
@item = Item.find(params[:id])
end
def item_params
params.require(:item).permit(:name, :url, :full_address, :city, :country, :category, :ratings_attributes => [:rating, :comment])
end
def user_signed_in?
#TODO: should display should sign in to rate an item
redirect_to(root_url) unless signed_in?
end
end