Ruby on Rails NoMethodError in FoodItemsController#create - ruby-on-rails

This is the error I am getting when I hit submit on my form for uploading an image. Can anyone help me out? I feel like the JSON serialize isnt working. which is causing the error.
class FoodItem < ApplicationRecord
mount_uploader :image, ImageUploader
serialize :image, JSON # If you use SQLite, add this line
belongs_to :user, optional: true
validates :name, :description, :resturant, :glutenfree, :vegan, presence: true
validates :description, length: {maximum: 1000, too_long: "%{count} characters is the maximum allowed"}
validates :title, length: {maximum: 140, too_long: "%{count} characters is the maximum allowed"}
end
here is my food controller,
class FoodItemsController < ApplicationController
before_action :set_food_item, only: %i[ show edit update destroy ]
before_action :authenticate_user!, except: [:index, :show]
# GET /food_items or /food_items.json
def index
#food_items = FoodItem.all.order("created_at desc")
end
# GET /food_items/1 or /food_items/1.json
def show
end
# GET /food_items/new FoodItem.new
def new
#food_item = current_user.food_items.build
end
# GET /food_items/1/edit
def edit
end
# POST /food_items or /food_items.json FoodItem.new(food_item_params)
def create
#food_item = current_user.food_items.build(food_item_params)
respond_to do |format|
if #food_item.save
format.html { redirect_to food_items_url(#food_item), notice: "Food item was successfully created." }
format.json { render :show, status: :created, location: #food_item }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #food_item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /food_items/1 or /food_items/1.json
def update
respond_to do |format|
if #food_item.update(food_item_params)
format.html { redirect_to food_items_url(#food_item), notice: "Food item was successfully updated." }
format.json { render :show, status: :ok, location: #food_item }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #food_item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /food_items/1 or /food_items/1.json
def destroy
#food_item.destroy
respond_to do |format|
format.html { redirect_to food_items_url, notice: "Food item was successfully destroyed." }
format.json { head :no_content }
end
end
# Use callbacks to share common setup or constraints between actions.
def set_food_item
#food_item = FoodItem.find(params[:id])
end
# Only allow a list of trusted parameters through.
def food_item_params
params.require(:food_item).permit(:name, :foodtype, :description, :ingrediants, :resturant, :glutenfree, :vegan, :image)
end
end
I believe the error is being caused by the image not being serialized to json because when I got to /public/images/tmp the images are being uploaded.

run rails db:migrate if title field not found foodItem_table
add title into food_item_params
def food_item_params
params.require(:food_item).permit(:name, :foodtype, :description, :ingrediants, :resturant, :glutenfree, :vegan, :image, :title)
end
3: run rails s

Related

undefined method `save' for nil:NilClass for my app

[enter image description here][1]
I keep getting this error message and can not figure out why it is. I believe it is because #resturant is nil. But I do not understand why it is nil.
Is there anyway to 'print or console log' the response so I can see what the problem is
[1]: https://i.stack.imgur.com/sHUrz.png
Here is the model
class Resturant < ApplicationRecord
mount_uploader :image, ImageUploader
serialize :image, JSON # If you use SQLite, add this line
belongs_to :user, optional: true
validates :name, :description, :location, :resturant, :glutenfree, :vegan, presence: true
validates :description, length: {maximum: 1000, too_long: "%{count} characters is the maximum allowed"}
validates :title, length: {maximum: 140, too_long: "%{count} characters is the maximum allowed"}
end
here is the controller:
class Resturant < ApplicationRecord
mount_uploader :image, ImageUploader
serialize :image, JSON # If you use SQLite, add this line
belongs_to :user, optional: true
validates :name, :description, :location, :resturant, :glutenfree, :vegan, presence: true
validates :description, length: {maximum: 1000, too_long: "%{count} characters is the maximum allowed"}
validates :title, length: {maximum: 140, too_long: "%{count} characters is the maximum allowed"}
end
# GET /resturants/new
def new
#resturant = Resturant.new
end
# GET /resturants/1/edit
def edit
end
# POST /resturants or /resturants.json
def create
#resturants = Resturant.new(resturant_params)
respond_to do |format|
if #resturant.save
format.html { redirect_to resturant_url(#resturant), notice: "Resturant was successfully created." }
format.json { render :show, status: :created, location: #resturant }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #resturant.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /resturants/1 or /resturants/1.json
def update
respond_to do |format|
if #resturant.update(resturant_params)
format.html { redirect_to resturant_url(#resturant), notice: "Resturant was successfully updated." }
format.json { render :show, status: :ok, location: #resturant }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #resturant.errors, status: :unprocessable_entity }
end
end
end
# DELETE /resturants/1 or /resturants/1.json
def destroy
#resturant.destroy
respond_to do |format|
format.html { redirect_to resturants_url, notice: "Resturant was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_resturant
#resturant = Resturant.find(params[:id])
end
# Only allow a list of trusted parameters through.
def resturant_params
params.require(:resturant).permit(:name, :genre, :description, :location, :glutenfree, :vegan, :image, :resturant)
end
end
You have a typo. (It often takes a second set of fresh eyes to see these.)
You have accidentally pluralized resturant in your create action but then are using the singular later on.
You have:
#resturants = Resturant.new(resturant_params)
Change it to:
#resturant = Resturant.new(resturant_params)
(You are also misspelling "Restaurant" throughout your entire application. It is up to you if you'd like to fix that or not. I know I myself have trouble spelling that one for some silly reason.)

How to limit number of uploads by user?

relatively new to ruby on rails and I'm creating a simple Uploads model for Paperclip images to be attached and displayed. I've got that all working well, but I want to limit a current user to upload no more than 6 images at any given time.
In what file and what code would I add this? It would be quite helpful to know this for any future model I create !
I'm assuming it's quite a small bit of code but I can't see an answer anywhere online... thanks !
my UploadsController (did a simple scaffolding and paperclip setup):
class UploadsController < ApplicationController
before_action :set_upload, only: [:show, :edit, :update, :destroy]
# GET /uploads
# GET /uploads.json
def index
#uploads = Upload.all
end
# GET /uploads/1
# GET /uploads/1.json
def show
end
# GET /uploads/new
def new
#upload = current_user.uploads.build
end
# GET /uploads/1/edit
def edit
end
# POST /uploads
# POST /uploads.json
def create
#upload = current_user.uploads.build(upload_params)
respond_to do |format|
if #upload.save
format.html { redirect_to #upload, notice: 'Upload was successfully created.' }
format.json { render :show, status: :created, location: #upload }
else
format.html { render :new }
format.json { render json: #upload.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /uploads/1
# PATCH/PUT /uploads/1.json
def update
respond_to do |format|
if #upload.update(upload_params)
format.html { redirect_to #upload, notice: 'Upload was successfully updated.' }
format.json { render :show, status: :ok, location: #upload }
else
format.html { render :edit }
format.json { render json: #upload.errors, status: :unprocessable_entity }
end
end
end
# DELETE /uploads/1
# DELETE /uploads/1.json
def destroy
#upload.destroy
respond_to do |format|
format.html { redirect_to uploads_url, notice: 'Upload was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_upload
#upload = Upload.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def upload_params
params.require(:upload).permit(:upload_title, :upload_description, :upload_datecreated, :user_id, :picture, :delete_picture)
end
end
Upload model:
class Upload < ActiveRecord::Base
belongs_to :user
has_attached_file :picture, styles: { large: "600x600#", medium: "300x300#", small: "150x150#", thumb: "50x50#" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :picture, content_type: /\Aimage\/.*\Z/
before_validation { image.clear if #delete_image }
def delete_picture
#delete_image ||= false
end
def delete_picture=(value)
#delete_image = !value.to_i.zero?
end
end
class Upload < ActiveRecord::Base
MAX_IMAGES = 6
validate :maximum_images
private
def count_valid_images
self.user.uploads.count
end
def maximum_images
errors.add(:base, "must have max #{MAX_IMAGES} images") if count_valid_images > MAX_IMAGES
end
end

Render action with parameters after form error

I have basic form that is accessed, for example via: http://url.com/rentals/new/dvd/10.
The problem is when form error happens I can't redirect it to the same page with the same
url segments and show the form error messages.
rentals_controller.rb:
def create
#rental = Rental.new(rental_params)
respond_to do |format|
if #rental.save
format.html { redirect_to #rental, notice: 'Rental was successfully created.' }
format.json { render :show, status: :created, location: #rental }
else
format.html { render :new }
format.json { render json: #rental.errors, status: :unprocessable_entity }
end
end
end
routes.rb
get 'rentals/new/dvd/:dvd_id' => 'rentals#new', as: :new_dvd_rental
I have the following models created:
dvd.rb
class Dvd < ActiveRecord::Base
has_many :rentals
has_many :users, through: :rentals
validates :title, presence: true
validates :year, inclusion: {in: 1900..Time.now.year.to_i}, :presence => {:message => 'Year must be from 1900 till current year.'}
validates :length, inclusion: {in: 1..999}, :presence => {:message => 'DVD length must be in minutes in range 1..999.'}
end
rental.rb
class Rental < ActiveRecord::Base
belongs_to :user
belongs_to :dvd
validates :user_id, presence: true
validates :total_price, presence: true
end
user.rb
class User < ActiveRecord::Base
has_many :rentals
has_many :dvds, through: :rentals
end
As well as rentals_controller.rb:
class RentalsController < ApplicationController
before_action :set_rental, only: [:show, :edit, :update, :destroy]
# GET /rentals
# GET /rentals.json
def index
#rentals = Rental.all
end
# GET /rentals/1
# GET /rentals/1.json
def show
end
# GET /rentals/new
def new
#rental = Rental.new
#users = User.all
#dvd = Dvd.find(params[:dvd_id])
end
# GET /rentals/1/edit
def edit
end
# POST /rentals
# POST /rentals.json
def create
#rental = Rental.new(rental_params)
respond_to do |format|
if #rental.save
format.html { redirect_to #rental, notice: 'Rental was successfully created.' }
format.json { render :show, status: :created, location: #rental }
else
format.html { render :new }
format.json { render json: #rental.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /rentals/1
# PATCH/PUT /rentals/1.json
def update
respond_to do |format|
if #rental.update(rental_params)
format.html { redirect_to #rental, notice: 'Rental was successfully updated.' }
format.json { render :show, status: :ok, location: #rental }
else
format.html { render :edit }
format.json { render json: #rental.errors, status: :unprocessable_entity }
end
end
end
# DELETE /rentals/1
# DELETE /rentals/1.json
def destroy
#rental.destroy
respond_to do |format|
format.html { redirect_to rental_url, notice: 'Rental was successfully deleted.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_rental
#rental = Rental.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def rental_params
params.require(:rental).permit(:dvd_id, :user_id, :rent_date, :return_date, :total_price, :returned)
end
end
I've tried to modify rental controller like this, but still do not know how to pass other segments like new and dvd:
render :action => "new", :dvd_id => params[:dvd_id]
Any ideas?
I think if you draw a more restful route like this
resources :dvds do
resources :rentals
end
you will get the routes like http://url.com/dvd/10/rentals/new
here you will always get dvd_id
and in rentals_controller create method look like
def create
#dvd = Dvd.find(params[:dvd_id])
#rental = Rental.new(rental_params)
respond_to do |format|
if #rental.save
format.html { redirect_to #rental, notice: 'Rental was successfully created.' }
format.json { render :show, status: :created, location: #rental }
else
format.html { render :new }
format.json { render json: #rental.errors, status: :unprocessable_entity }
end
end
end
-- Waiting for #Sanket's ideas
Routes
The issue will almost certainly be with your redirect_to method
The problem is that your controller doesn't know you're using a nested resource, and consequently when you redirect to an object, it will likely just take you to the simplest route it can find
I would try this:
def create
...
else
format.html { render your_nested_resource_path(dvd_id: params[:dvd_id], other: params[:params]) }
...
end
This allows you to send the request to the nested route, which Rails won't route to without support

NoMethodError in ProductsController#create

I am working through "Agile Web Development with Rails 4" and I've run in to this issue in Chapter 7, Task B: Validation and Unit Testing. Any help would be appreciated.
When I try to add a new entry this is the error I get.
undefined method `titles' for #Product:0x007fa6fcbf28e0
Extracted source (around line #30):
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render action: 'show', status: :created, location: #product }
else
if #product.save is line 30.
This started after adding these lines to my products.rb in /rails/depot_a/app/models
class Product < ActiveRecord::Base
validates :titles, :description, :image_url, presence: true
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
validates :image_url, allow_blank: true, format: {
with: %r{\.(gif|jpg|png)\Z}i,
message: 'must be a URL for GIF, JPG, or PNG image.'
}
end
This is my products_controller.rb in /rails/depot_a/app/controllers which was mentioned in the error.
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
# GET /products
# GET /products.json
def index
#products = Product.all
end
# GET /products/1
# GET /products/1.json
def show
end
# GET /products/new
def new
#product = Product.new
end
# GET /products/1/edit
def edit
end
# POST /products
# POST /products.json
def create
#product = Product.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render action: 'show', status: :created, location: #product }
else
format.html { render action: 'new' }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
#product.destroy
respond_to do |format|
format.html { redirect_to products_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product
#product = Product.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def product_params
params.require(:product).permit(:title, :description, :image_url, :price)
end
end
ruby 2.0.0p353
Rails 4.0.3

Show a count of total number of pins (images) in database on homepage?

OK - So I have a PINS models that basically allows users to upload images (pins). On the main page of the site I would like to query and show users how many total images have been loaded into the database - I use paperclip and devise: What do I need to do to count and show the total number of Pins ? Thank everyone for taking the time to help with this inquiry :)
Here is my pins model:
class Pin < ActiveRecord::Base
attr_accessible :description, :image, :tag_list, :image_remote_url
has_attached_file :image, styles: { medium: "320x300>" }
validates :description, presence: true
validates :user_id, presence: true
validates_attachment :image, presence: true,
content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', ] },
size: { less_than: 100.megabytes }
belongs_to :user
has_attached_file :image, styles: { medium: "320x300"}
def image_remote_url=(url_value)
self.image = URI.parse(url_value) unless url_value.blank?
super
end
acts_as_taggable
def next_image
self.class.where('id > ?', self.id).order('id asc').first
end
def previous
self.class.where('id < ?', self.id).order('id desc').first
end
end
and my controller:
class PinsController < ApplicationController
before_filter :authenticate_user!, except: [:show, :index]
# GET /pins
# GET /pins.json
def index
if params[:tag]
#pins = Pin.tagged_with(params[:tag]).order("created_at desc").paginate(:page => params[:page], :per_page => 100)
else
#pins = Pin.order("created_at desc").page(params[:page]).per_page(100)
#respond_to do |format|
#format.html
#format.atom
end
end
# #pins = Pin.all
#end
#end
# GET /pins/1
# GET /pins/1.json
def show
#pin = Pin.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #pin }
end
end
# GET /pins/new
# GET /pins/new.json
def new
#pin = current_user.pins.new
#pin_count = Pin.count
respond_to do |format|
format.html # new.html.erb
format.json { render json: #pin }
end
end
# GET /pins/1/edit
def edit
#pin = current_user.pins.find(params[:id])
end
# POST /pins
# POST /pins.json
def create
#pin = current_user.pins.new(params[:pin])
respond_to do |format|
if #pin.save
format.html { redirect_to #pin, notice: 'Pin was successfully created.' }
format.json { render json: #pin, status: :created, location: #pin }
else
format.html { render action: "new" }
format.json { render json: #pin.errors, status: :unprocessable_entity }
end
end
end
# PUT /pins/1
# PUT /pins/1.json
def update
#pin = current_user.pins.find(params[:id])
respond_to do |format|
if #pin.update_attributes(params[:pin])
format.html { redirect_to #pin, notice: 'Pin was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #pin.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pins/1
# DELETE /pins/1.json
def destroy
#pin = current_user.pins.find(params[:id])
#pin.destroy
respond_to do |format|
format.html { redirect_to pins_url }
format.json { head :no_content }
end
end
end
#def pin_params
#params.require(:pin).permit(:description, :image)
#end
You're on One month Rails aren't you? Brilliant Tutorial :)
In your Pin Controller include the code in the Action you want (in your example the show action):
def show
# your other code here
#pin_count = Pin.count
# #count is now available in your view for `show`
end
Than you can call in your view => <%= #pin_count %>

Resources