ruby on rails - creating an object with has_many association results in item can not be blank -


i have following associations , related controller, in form adding every field should be. still error ratings item can't blank when try create item. using rails 4.0 . did searched extensively not still find doing wrong. thankyou!

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 |format|       if @item.save         #todo create rating here (first rating of item)         flash[:success] = "welcome inmyopnion"         format.html { redirect_to @item, notice: 'item 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 rate item     redirect_to(root_url) unless signed_in?   end end 

simplify controller! since allowing nested_attributes should sufficient:

@item = item.create(params[:item]) 

the problem might caused @rating object not being saved.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -