[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.)
Related
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
I am trying to set the gender validation depending on the penultimate digit of the PESEL number (if the digit is even, then the gender is 'female'). For now my Profile.rb look like that:
class Profile < ApplicationRecord
enum gender: %i[male female]
validates :first_name, presence: true, on: :update
validates :last_name, presence: true, on: :update
validates :gender, presence: true, on: :update
validates :pesel, presence: true, on: :update
validates :contact_number, presence: true, on: :update
validates :pesel, format: { with: /\A(\d{11})\z/ }, on: :update
validate :gender_correct?
def gender_correct?
return self.pesel.blank?
if self.pesel[-2].to_i % 2 != 0
pesel_gender = 'male'
else
pesel_gender = 'female'
end
if pesel_gender != self.gender
errors.add(:gender, t('activerecord.errors.models.profile.attributes.gender.wrong'))
end
end
Unfortunately it doesn't work. Other validations works fine.
EDIT:
My update action:
def update
#profile = Profile.find(params[:id])
respond_to do |format|
#profile.avatar.attach(params[:avatar]) if params[:avatar].present?
if #profile.errors.empty? && #profile.update(profile_params)
#profile.onboarded = true
#profile.save
#profile.fill_info!
#profile.assign_dispensary
format.html { redirect_to authenticated_root_path, notice: t('.update.success') }
format.json { render :show, status: :ok, location: #profile }
else
format.html { render 'pages/info', alert: t('.update.error') }
format.json { render json: #profile.errors, status: :unprocessable_entity }
end
end
end
If i tried to update profile with blank first/last name, pesel, gender or contact number,then an error is displayed below text field.
Before update:
https://drive.google.com/file/d/1uS30WKLBFt5jcUUycI4CQblnEOpkrWEc/view?usp=sharing
After update:
https://drive.google.com/file/d/1HJqk-0opJdoZQ37CkPwscfL8Ohb19n6A/view?usp=sharing
I wanted to display error "PESEL does not match the set gender. Correct the PESEL number." under gender text field if PESEL gender doesn't match selected gender. Is that enough info? Or should I add something else?
Im trying to upload a photo through my Rails app and everything is fine until I click on "update...". Then it throws me an "ActionController::UnknownFormat" error and fails. Here you can find the form I'm using, the update controller and the model I'm referring to.
Form:
<%= form_with(model: current_user, local: true, html: {multipart: true}) do |form| %>
<div class="field">
<%= form.label :profile_pic %>
<%= form.file_field :profile_pic, id: :profile_pic %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
Update method:
def update
#user = current_user
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
render action: :edit
end
end
end
Error seems to be here:
respond_to do |format|
model:
require 'digest'
class User < ApplicationRecord
mount_uploader :profile_pic, ProfilePicUploader
attr_accessor :password
before_save :encrypt_new_password
after_create :build_profile
has_one :profile
has_many :trips
has_many :comments, through: :trips, source: :comments
has_many :posts, through: :trips, source: :posts
scope :recent_comments, ->{where("comments.created_at > ? AND user_id = ?", [6.months.ago, self.id]).limit(3)}
#friends
has_many :users
validates :email, uniqueness: {case_sensitive: false, message: 'El correo debe ser Ășnico'}, length: {in: 6..50, too_short: "debe tener al menos %{count} caracteres"}, format: {multiline: true,with: /^.+#.+$/, message: "formato de correo no valido"}
validates :password, confirmation: true, length: {within: 4..20}, presence: {if: :password_required?}
validates :password_confirmation, presence: true
def self.authenticate(email,password)
user = find_by_email(email)
return user if user && user.authenticated?(password)
end
def authenticated?(password)
self.hashed_password == encrypt(password)
end
protected
def encrypt_new_password
return if password.blank?
self.hashed_password = encrypt(password)
end
def password_required?
hashed_password.blank? || password.present?
end
def encrypt(string)
Digest::SHA1.hexdigest(string)
end
def build_profile
Profile.create(user: self, name: self.name, bio:"Im using Tripper!")
end
end
If anyone could tell me please what did I do wrong...
You have used the respond_to block, but you didn't specify the format in which edit action should be rendered.
Try updating the update action as below:
def update
#user = current_user
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
format.html { render 'edit'} # Specify the format in which you are rendering the 'edit' page
format.json { render json: #user.errors } # If required, specify a json format as well
end
end
end
Try to the following by updating the update action
def update
#user = current_user
respond_to do |format|
if #user.update(user_params)
flash[:notice] = 'User was successfully updated.'
format.html {redirect_to user_path(#user) }
format.json { render :show, status: :ok, location: #user }
else
render action: :edit
end
end
end
Hope to help
I have a text_field that I want set 3 validation on this. In this text_field I get reporter's phone number. Each reporter has_one reporterprofile. I want when reporter enter his phone_number, I check validates_numericality_of and validates_length_of and if these two are true, then check uniqueness validation, If this phone_number is new, thats ok, I create a reporterprofile and redirect_to reporterprofile by this new id, But if this phone_number is exist, I want page is redirect_to this reporterprofile without created new reporter.
reporter.rb
class Reporter < ActiveRecord::Base
has_one :reporterprofile
before_create :build_reporterprofile
validates :phone_number, uniqueness: true
validates_numericality_of :phone_number
validates_length_of :phone_number, :minimum => 11, :maximum => 11
end
reporters_controller.rb
def create
#reporter = Reporter.new(reporter_params)
respond_to do |format|
if #reporter.save
format.html { redirect_to edit_reporterprofile_path(:id => #reporter.reporterprofile), notice: 'Reporter was successfully created.' }
format.json { render action: 'show', status: :created, location: #reporter }
else
if
format.html { render action: 'new' }
format.json { render json: #reporter.errors, status: :unprocessable_entity }
end
end
end
end
I can redirect_to edit_reporterprofile_path when reporter doesn't save, but if I do this, numerically and length validations are don't check. How can I redirect reporter that is exist to his profile?
First, check if a Reporter with the given phone number exists. If so, redirect to the reporterprofile path. Otherwise, create the new reporter. There are various ways to organize the logic to handle this. Here it is all shoved into the "create" action of the reporters controller.
def create
existing_reporter = Reporter.includes(:reporterprofile).find_by(phone_number: reporter_params[:phone_number])
if existing_reporter
redirect_to reporterprofile_path(existing_reporter.reporterprofile)
else
#reporter = Reporter.new(reporter_params)
respond_to do |format|
if #reporter.save
format.html { redirect_to edit_reporterprofile_path(:id => #reporter.reporterprofile), notice: 'Reporter was successfully created.' }
format.json { render action: 'show', status: :created, location: #reporter }
else
if
format.html { render action: 'new' }
format.json { render json: #reporter.errors, status: :unprocessable_entity }
end
end
end
end
end
I'd start by populating the validates method with more than what you've got now. This will remove the dependency on the other two methods you have, which should go to fixing some of the issue:
validates :phone_number,
length: { is: 6 },
numericality: true,
uniqueness: true
I have two model class,
class Designation < ActiveRecord::Base
attr_accessible :name
validates :name, presence: true, uniqueness: { case_sensitive: false }
has_many :employee_details
accepts_nested_attributes_for :employee_details
end
and
class EmployeeDetail < ActiveRecord::Base
belongs_to :Designation
attr_accessible :bloodGroup, :dob, :doc, :doj, :empId, :name, :panNo, :status, :Designation
end
I have generated default scaffold for EmployeeDetail. from EmployeeDetail page when i tried to create and enter integer value in designation textbox, it gives me error
ActiveRecord::AssociationTypeMismatch in EmployeeDetailsController#create
Designation(#81846160) expected, got String(#75419260).
can anyone help me to sortout this problem?
EmployeeDetailController#create:-
def create
#employee_detail = EmployeeDetail.new(params[:employee_detail])
respond_to do |format|
if #employee_detail.save
format.html { redirect_to #employee_detail, notice: 'Employee detail was successfully created.' }
format.json { render json: #employee_detail, status: :created, location: #employee_detail }
else
format.html { render action: "new" }
format.json { render json: #employee_detail.errors, status: :unprocessable_entity }
end
end
end
When you associate any model, you should use the lowercase version of the model name.
Change:
belongs_to :Designation
to:
belongs_to :designation