Rails - Model not saving to db - ruby-on-rails

I'm completing this airbnb clone course (https://code4startup.com/projects/build-airbnb-with-ruby-on-rails-level-1) but have diverted a bit in order to complete my own project; a marketplace for education camps. Therefore I've added an additional model 'Courses'. It now has User>Listing>Course. This Courses model is working in rails console but not saving to my database when I'm running the server. Any suggestions would be appreciated...
Error Message
ActiveRecord::RecordInvalid in CoursesController#create
Validation failed: Listing must exist
Models
class User < ApplicationRecord
has_many :listings
has_many :courses, :through => :listings
end
class Listing < ApplicationRecord
belongs_to :user
has_many :courses
validates :listing_type, presence: true
validates :course_type, presence: true
validates :accommodate, presence: true
end
class Course < ApplicationRecord
belongs_to :listing
validates :curriculum_type, presence: true
validates :course_places, presence: true
end
Course Controller
class CoursesController < ApplicationController
before_action :set_course, except: [:index, :new, :create]
before_action :authenticate_user!, except: [:show]
def index
#courses = current_user.courses
end
def new
#course = current_user.courses.build
end
def create
#course = current_user.courses.build(course_params)
if #course.save!
redirect_to course_listing_path(#course), notice: "Saved..."
else
render :new, notice: "Something went wrong..."
end
end
def show
end
def listing
end
def pricing
end
def description
end
def photo_upload
end
def amenities
end
def location
end
def update
if #course.update(course_params)
flash[:notice] = "Saved..."
else
flash[:notice] = "Something went wrong..."
end
redirect_back(fallback_location: request.referer)
end
private
def set_course
#course = Course.find(params[:id])
end
def course_params
params.require(:course).permit(:name, :curriculum_type, :summary, :address, :course_places, :start_date, :finish_date, :price)
end
end
Routes
Rails.application.routes.draw do
root 'pages#home'
devise_for :users,
path: '',
path_names: {sign_in: 'login', sign_out: 'logout', edit: 'profile', sign_up: 'registration'},
controllers: { omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations' }
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :users, only: [:show]
resources :listings, except: [:edit] do
member do
get 'listing'
get 'pricing'
get 'description'
get 'photo_upload'
get 'amenities'
get 'location'
end
end
resources :courses, except: [:edit] do
member do
get 'listing'
get 'pricing'
get 'description'
get 'photo_upload'
get 'amenities'
get 'location'
end
end
end

below you can read my comments with the # sign
You are trying to save an object Course that has belongs_to listings so it is expected that it has as course.listing_id the id of an existing Listing
def create
#course = current_user.courses.build(course_params)
# You need to set #course.listing_id to an existing Listing
# You need to find that listing and save it in a variable.
# I am not getting into your logic, because your code is confused and need many adjustments
listing = Listing.find() # include hear your logic to find an existing listing from the db
#course.listing_id = listing.id
if #course.save!
redirect_to course_listing_path(#course), notice: "Saved..."
else
render :new, notice: "Something went wrong..."
end
end

Related

Updating a referenced entity through the create form of another

I have 2 models that are linked through a joint table:
class Dailyreport < ApplicationRecord
max_paginates_per 9
belongs_to :owner
has_many :dailyreport_issues
has_many :issues, through: :dailyreport_issues
accepts_nested_attributes_for :issues, allow_destroy: true
end
class Issue < ApplicationRecord
belongs_to :project
belongs_to :owner
has_many :dailyreport_issues
has_many :dailyreports, through: :dailyreport_issues
max_paginates_per 10
before_create { |issue| issue.jiraid = issue.jiraid.upcase }
validates :jiraid, uniqueness: true
validates :jiraid, :project, :owner, :time_forecast, :time_real, presence: true
validates :jiraid, format: { with: /\b[a-zA-Z]{2,6}-[1-9]\d{0,3}\b/, message: 'must follow this format ABCXYZ-9999' }
validates :time_real, numericality: { only_float: true }
validates :time_forecast, numericality: { only_float: true }
end
class DailyreportIssue < ApplicationRecord
belongs_to :dailyreport
belongs_to :issue
end
I use nested forms 'cocoon gem' to generate issues inside the create form of the dailyreport.
I successfully implemented that with these 2 controllers:
class DailyreportsController < ApplicationController
helper DailyreportsHelper
before_action :define_dailyreport, only: [:edit, :show, :update, :destroy]
def index
#dailyreports = Dailyreport.all.order(created_at: :desc).page params[:page]
end
def new
#dailyreport = Dailyreport.new
#dailyreport.issues.build
#issues = Issue.all.order(created_at: :desc)
end
def edit
end
def show
end
def owner_dailyreport
#owner_dailyreport = current_user.owner.dailyreports
end
def create
#dailyreport = Dailyreport.new(dailyreport_params)
#dailyreport.issues.each do |cr_issue|
call_jira_api("https://agenceinspire.atlassian.net/rest/api/3/issue/#{cr_issue.jiraid}")
if #response_output_issues.key?('errors')
flash.alert = "Please check if #{cr_issue.jiraid} exists and is available on JIRA"
no_api_reponse
else
issue_details_from_jira(cr_issue)
issue_time_real_from_jira(cr_issue)
end
if #dailyreport.save!
redirect_to #dailyreport, notice: 'Dailyreport was successfully created.'
else
render :new
end
end
end
def update
if #dailyreport.update(dailyreport_params)
redirect_to #dailyreport, notice: 'Dailyreport was successfully updated.'
else
render :edit
end
end
def destroy
if current_user.admin? || current_user.email == #dailyreport.owner.email
#dailyreport.destroy
else
admin_only_access
end
previous_page
end
private
def dailyreport_params
params.require(:dailyreport).permit(
:comment,
:owner_id,
issues_attributes: [
:jiraid,
:project_id,
:owner_id,
:time_forecast,
:time_real,
:departement,
:retour_test,
:status,
:_destroy
]
)
end
def define_dailyreport
#dailyreport = Dailyreport.find(params[:id])
end
end
class IssuesController < ApplicationController
require 'net/http'
require 'uri'
before_action :define_issue, only: [:show, :edit, :update, :destroy]
before_action :admin_only_access, only: [:destroy, :edit, :update]
def index
#issues = Issue.all.order(created_at: :desc).page params[:page]
end
def search
if params[:search].blank?
redirect_to issues_path and return
else
#parameter = params[:search].downcase
#results = Issue.all.where('lower(jiraid) LIKE :search', search: "%#{#parameter}%").page params[:page]
end
end
def new
#issue = Issue.new
end
def show
call_jira_api("https://agenceinspire.atlassian.net/rest/api/3/issue/#{#issue.jiraid}")
if #response_output_issues.key?('errors')
flash.alert = "Please check if #{#issue.jiraid} exists and is available on JIRA"
no_api_reponse
else
issue_details_from_jira(#issue)
yes_api_response
end
end
def create
#issue = Issue.new(issue_params)
# Check if issue exists on JIRA
unless call_jira_api("https://agenceinspire.atlassian.net/rest/api/3/issue/#{#issue.jiraid}")
flash.alert = "Please check if #{#issue.jiraid} exists and is available on JIRA"
end
# Get issue details from JIRA
issue_details_from_jira(#issue)
issue_time_real_from_jira(#issue)
# Save the issue
if #issue.save
flash.notice = "Issue #{#issue.jiraid} created"
redirect_to issues_path and return
else
flash.alert = "There was a problem saving #{#issue.jiraid}, check if all the fields are filled on the JIRA issue"
end
end
def edit
end
def update
if #issue.update(issue_params)
redirect_to issues_path
else
render :edit, status: :unprocessable_entity
end
end
def destroy
if current_user.admin?
#issue.destroy
else
admin_only_access
end
previous_page
end
private
def issue_params
params.require(:issue).permit(
:jiraid,
:project_id,
:owner_id,
:time_forecast,
:time_real,
:departement,
:retour_test,
:status
)
end
def define_issue
#issue = Issue.find(params[:id])
#issue_owner = Owner.find_by(params[:current_user])
end
end
My routesRails.application.routes.draw do
get '/search', to: 'issues#search'
get '/home/jira', to: 'home#jira'
get '/dailyreports/owner_dailyreport/:id', to: 'dailyreports#owner_dailyreport', :as => 'my_crs'
resources :projects
resources :issues
resources :departements
resources :owners
resources :dailyreports
# Devise routes
devise_scope :user do
get 'users', to: 'devise/sessions#new'
end
devise_for :users
authenticated :user do
root to: 'home#index', as: :authenticated_root
end
root to: redirect('/users/sign_in')
end
I am trying to implement an update or create process:
Check if the JIRAID exists in my DB
If it doesn't just get the data and save the dailyreport.
If it does, I call the API and get its updated details then update it and save the dailyreport.
And here I found some issues with the code I tried.
First when I update the issue then try to save the dailyreport, it throws the validation error (Jiraid exists) because the dailyreport.save is trying to update the issue again.
I also tried this:
def create
#dailyreport = Dailyreport.new(dailyreport_params)
issues_attributes = params[:dailyreport][:issues_attributes]
p("///////////////////////////////////ISSUES_ATTRIBUTES#{issues_attributes}")
issues_attributes.each do |_, issue_attributes|
p("~~~~~~~~~~~~~~~~~~~~~~ISSUE_ATTRIBUTE#{issue_attributes}")
# Call the JIRA API and check for errors
call_jira_api("https://agenceinspire.atlassian.net/rest/api/3/issue/#{issue_attributes["jiraid"]}")
if #response_output_issues.key?('errors')
flash.alert = "Please check if #{issue_attributes["jiraid"]} exists and is available on JIRA"
return
end
# Update the issue attributes with details from the JIRA API
issue_details_from_jira(issue_attributes)
issue_time_real_from_jira(issue_attributes)
p("~~~~~~~~~~~~~~~~~~~~~~JIRA ID IN THE DB: #{issue.jiraid}")
# Check if the issue already exists in the database
issue = Issue.find_by(jiraid: issue_attributes["jiraid"])
if issue
issue_details_from_jira(issue)
issue_time_real_from_jira(issue)
# Update the existing issue
issue.update(
time_forecast: issue.time_forecast,
time_real: issue.time_real,
status: issue.status
)
else
# Build and save a new issue if it doesn't exist
#dailyreport.issues.build(issue_attributes)
end
end
I know I have an issue here:
issue_details_from_jira(issue_attributes)
issue_time_real_from_jira(issue_attributes)
I am going to have to create an object to pass to my methods. But i don't know how.
I couldn't update the issue from the dailyreport controller too, so I tried passing the update method (+ the id) inside the strong params of the dailyreport. That resulted in a ForbiddenAttributes error.
I actually need a lead of how to approach this, not a specific solution. I think that my approach is wrong.
thank you in advance

Couldn't find Course without an ID

When I try to access app/views/companies/courses/show.html.erb(which is redirected after app/views/companies/courses/new.html.erb), rails server says that it cannot find a course without an ID.
Also, when I run Course.all on rails console, the courses have the correct id, the correct description and the correct company id but no name attribute.
App/controllers/companies/courses_controller:
class Companies::CoursesController < ApplicationController
before_action :authenticate_company!
def new
#course = Course.new
end
def create
#course = current_company.courses.create(course_params)
if #course.save
redirect_to companycourse_path(:course => #course.id)
else
render 'new'
end
end
def show
#course = current_company.courses.find(params[:id])
end
def index
#courses = current_company.courses.all
end
private
def course_params
params.require(:course).permit(:title, :description)
end
end
App/models/course.rb:
class Course < ApplicationRecord
belongs_to :company
end
App/models/company.rb:
class Company < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :courses
end
Config/routes.rb:
Rails.application.routes.draw do
devise_for :companies
devise_for :users
root 'static_pages#home'
get 'users/:id' => 'users#show'
resources :users, only: [:show]
get 'companies/:id' => 'companies#show'
resources :companies, only: [:show] do
resources :courses, only: [:show,:new,:create,:index]
end
devise_scope :user do
get 'signup', to: 'users/registrations#new'
get 'login', to: 'users/sessions#new'
end
devise_scope :company do
get 'companysignup', to: 'companies/registrations#new'
get 'companylogin', to: 'companies/sessions#new'
get 'newcourse', to:'companies/courses#new'
post 'newcourse', to:'companies/courses#create'
get 'companycourse', to:'companies/courses#show'
get 'companycoursesindex', to:'companies/courses#index'
end
end
I had a similar problem building my app not long ago and my problem was coming from controllers.
In your routes.rb I would add resources :companies, :has_many => :courses.I also would add a validation to your course model in models/course.rb to make sure that when you save it to the database your object has a title: class Course < ApplicationRecord
belongs_to :company validates :title, presence: :true
end
Also try using this or something along lines in your courses_controller.rb instead of your current code:
def create
#company = find_company
#course = Course.new(course_params)
#course.company_id = current_company.id
if #course.save
your conditions here
else
your conditiona here
end
end
private
def find_company
params.each do |name, value|
if name == 'company_id'
return #company = Company.find(value.to_i)
end
end
nil
end
I hope it helps.

Why after validation of post title, when I have got validation error, browser passes to Rails server the previous value of post title?

I get posts by :title instead :id
routes.rb:
Rails.application.routes.draw do
#RSS
get 'feed' => 'posts#feed'
get 'archive' => 'posts#archive'
devise_for :users, controllers: { omniauth_callbacks: "callbacks" }
root to: "posts#index"
resources :posts, param: :title do
resources :comments, only: [:new, :create, :destroy]
resources :images do
resources :comments, only: [:new, :create]
end
resources :links do
resources :comments, only: [:new, :create]
end
resources :photos, only: [:new, :create,:destroy]
resources :songs, only: [:new, :create, :destroy]
end
post_controller:
class PostsController < ApplicationController
before_action :authenticate_user!, only: [:new, :create, :show]
respond_to :html, :json, :rss, :atom
def index
if params[:search].blank?
#posts = Post.includes(:comments, :photos).all
else
#search = Post.search do
fulltext params[:search]
end
#posts = #search.results
end
respond_with(#posts)
end
def show
set_post
end
def new
#post = Post.new
end
def edit
#post = Post.find_by(title: params[:title])
end
def create
#post = Post.new(post_params)
#post.errors.add(:base, :invalid) unless #post.save
respond_with(#post)
end
def update
set_post # this #post dont get post becouse browser pass wrong title and rails dont find it
if #post.valid? # here error becouse #post hasnt find
#post.update(post_params)
else
#post.errors.add(:base, :invalid)
end
respond_with(#post)
end
def destroy
set_post
#post.destroy
respond_with(#post)
end
def feed
#posts = Post.all.reverse
respond_with(#posts)
end
def archive
#posts_by_year = Post.limit(300).all.order("created_at DESC").
group_by {|post| post.created_at.beginning_of_year}
end
private
def set_post
#fix N+1 queries and find by posts title
#post = Post.includes(:comments, :photos, :links).find_by(title: params[:title])
end
def post_params
params.require(:post).permit(:title, :content)
end
end
When I create new post, if I include in my post title a dot, I get from Rails error. Therefore I use validation format: method for this case.
post.rb:
class Post < ActiveRecord::Base
#overwrite the to_param for changing routes from posts/id to posts/title
def to_param
title
end
has_many :comments, dependent: :destroy, as: :commentable
has_many :images, dependent: :destroy
has_many :links, dependent: :destroy
has_many :photos, dependent: :destroy
has_many :songs, dependent: :destroy
validates :content, presence: true
validates :title, presence: true, length: { maximum: 100 }
validates :title, format: { without: /\./,
message: "must be without dot" }
searchable do
text :title, :content
end
end
After this, when I update the post,my validation format method works and I get my validation message 'must be without dot'. Well. I delete in my post title input field dots and submit form. Now browser send to server previous post title value with dot.
Started PATCH "/posts/my%20test%20post%20title%20with%20dot." for 127.0.0.1 at 2017-01-26 11:57:34 +0300
ActionController::RoutingError (No route matches [PATCH] "/posts/my%20test%20post%20title%20with%20dot."):
Therefore rails can't find post by title with dot an I get the error.
What can I solve this problem? Maybe :title instead :id in this case is bad idea?
I assume you're using form_for? Rails will set the title on the post object then run validation. When it fails it will display the edit view, form_for will then use the to_param method to set the url, which will use the posts updated title. When you try and update again it'll use the title from the url to try and find the post, but won't be able to because there isn't a post in the database with that title.
You should use something like friendly_id but if you really want to roll your own then a simple implementation would be to have a slug column which gets set based on the title after_validation but obviously you're going to have to make sure it's unique so personally I'd switch to friendly id or another gem that deals with slugs.

Has many through or Has and belongs to many missing ID

Just trying to create a simple workout log here I'm getting this error when I try and create weights
"Workout ID must exist"
Models
class Workout < ApplicationRecord
belongs_to :user
has_many :exercises
has_many :weights, through: :exercises
accepts_nested_attributes_for :exercises, :allow_destroy => true
accepts_nested_attributes_for :weights, :allow_destroy => true
validates :bodypart, presence: true, length: { maximum: 255 }
end
class Weight < ApplicationRecord
belongs_to :exercise
belongs_to :workout
validates :amount, presence: true, length: { maximum: 255 }
validates :reps, presence: true, length: { maximum: 255 }
end
class Exercise < ApplicationRecord
belongs_to :workout
has_many :weights
accepts_nested_attributes_for :weights
validates :name, presence: true
validates_associated :weights
end
After reading a few things I thought that a has many through would be the option for these associations but now I'm not so sure. When I try and create a weight for exercise I get the exercise ID but can't seem to get the workout ID despite a number of attempts. I'm not sure if its simply a controller issue or if Im missing something bigger here.
My Current Weights Controller
class WeightsController < ApplicationController
before_action :authenticate_user!
def new
#weight = Weight.new
end
def create
#exercise = Exercise.find(params[:exercise_id])
#weight = #exercise.weights.build(weight_params)
if #weight.save
flash[:notice] = "Set saved"
redirect_to exercise_path(#exercise)
else
redirect_to exercise_path(#exercise)
flash[:notice] = "#{#weight.errors.full_messages.to_sentence}"
end
end
def edit
end
def update
end
def destroy
weight = Weight.find(params[:id])
#weight.destroy
redirect_to root_path
end
private
def weight_params
params.require(:weight).permit(:amount, :reps)
end
end
Routes.rb
Rails.application.routes.draw do
devise_for :users, controllers: { omniauth_callbacks: "callbacks" }
root 'articles#index'
get '/demo', to: 'static_pages#demo'
get '/about', to: 'static_pages#about'
get '/test', to: 'static_pages#index'
resources :articles
resources :workouts do
resources :exercises
end
resources :exercises do
resources :weights
end
resources :workouts do
member do
put :is_finished
put :unfinish
end
end
resources :exercises do
member do
put :is_finished
put :unfinish
end
end
resources :books, :only => :index
end
Exercises controller
class ExercisesController < ApplicationController
before_action :authenticate_user!
# before_action :set_exercise, except: [:index, :new, :create]
def new
#exercise = Exercise.new
#exercise.weights.new
end
def index
#workout = Workout.find(params[:workout_id])
#exercise = #workout.exercises
end
def create
#workout = Workout.find(params[:workout_id])
#exercise = #workout.exercises.build(exercise_params)
if #exercise.save
redirect_to workout_exercise_path(#workout, #exercise)
flash[:notice] = "Exercise created, enter weight and reps for your first set"
else
redirect_to #workout
flash[:notice] = "#{#exercise.errors.full_messages.to_sentence}"
end
end
def edit
end
def update
#exercise = Exercise.find(params[:id])
if #exercise.update_attributes(exercise_params)
redirect_to exercise_path(#exercise)
else
flash[:notice] = "Something went wrong"
end
end
def show
#exercise = Exercise.find(params[:id])
#weights = #exercise.weights.order('created_at DESC').paginate(page: params[:page], per_page: 5)
end
I do have an ID column for workout_id set on my Weights model but it always populates NULL whenever I can manage to create an exercise. Also, in the rails console I can find a workout and call #workout.weights and it returns the weights associated with the workout just fine. I just can't get the workout ID to populate in Weight model. Wondering if has and belongs to many would be better OR if my has many through is just set up wrong. I did try "inverse_of" without any luck. Any help would be appreciated.
The answer is quite simple. To add reverse functionality, you have to explicitly state it, through the exercise.
in weight.rb remove belongs_to :workout and add the following
def workout
self.exercise.workout
end
Perhaps you will need to add logic to avoid nilClass errors.
Now you do have #weight.workout through #weight.exercise

Uninitialized Constant in Namespace Controllers

I haven't had noobie routing errors in a while, but now that I'm using a namespace I don't seem to understand how to trace them...
uninitialized constant ShiftedCommerce::BaseItemsController::Item
So what exactly is this saying? There's no Item model associated with the BaseItemsController within my namespace?
I don't know why there's a trailing ::item, I don't think it should be there.
Another reason I think something strange is going on is because if I change ANYTHING in the BaseItemController, the page will render once. Then If I reload the page, the same error comes back up. It's extremely frustrating.
Here is my BaseItemControlller
class ShiftedCommerce::BaseItemsController < ApplicationController
before_action :set_base_item, only: [:show, :edit, :update, :destroy]
# GET /items
# GET /items.json
def index
#base_items = BaseItem.all
#line_item = LineItem.new
#cart = current_cart
#title = "Store"
end
# GET /items/1
# GET /items/1.json
def show
#cart = current_cart
#line_item = LineItem.new
end
# GET /items/new
def new
#base_item = BaseItem.new
end
and my model...
class ShiftedCommerce::BaseItem < ActiveRecord::Base
has_many :line_items, :through => :items
has_many :items
has_many :sizes, :through => :items
has_many :colors, :through => :items
before_destroy :ensure_not_referenced_by_any_line_item
validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
validates :title, :uniqueness => true
def one_record_of_variance
self
end
def has_no_variance
end
def is_base_item?
return true if self.class.name == "BaseItem"
end
def is_item?
return true if self.class.name == "Item"
end
private
# ensure that there are no line items referencing this product
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, 'Line Items present')
return false
end
end
end
Here are my paths:
App/controllers/shifted_commerce/base_items_controller.rb
App/models/shifted_commerce/models/base_item.rb

Resources