Building active record query - ruby-on-rails

I'm trying to build a query such that if a driver sends an offer to a ride, that ride no longer shows up in the collection rendered in the index view.
I've tried so many variations and I'm still getting all the rides. Even the ones Ive sent an offer to.
lang - ruby
class Driver < ApplicationRecord
belongs_to :user
has_many :offers
has_many :rides
end
class User < ApplicationRecord
has_many :rides
has_one :driver
end
class Ride < ApplicationRecord
validates :to, presence: true
validates :from, presence: true
validates :directions_from, presence: true
has_many :offers
belongs_to :user
belongs_to :driver, optional: true
end
lang - ruby
class Driver < ApplicationRecord
belongs_to :user
has_many :offers
has_many :rides
end
class User < ApplicationRecord
has_many :rides
has_one :driver
end
class Ride < ApplicationRecord
validates :to, presence: true
validates :from, presence: true
validates :directions_from, presence: true
has_many :offers
belongs_to :user
belongs_to :driver, optional: true
end
class Offer < ApplicationRecord
belongs_to :ride
belongs_to :driver
end
def index
#location = current_user.currently_at
#rides = Ride.includes(:driver).where(from: #location).select do |ride|
ride.offers.map do |offer|
offer.driver.user != current_user
end
end
#offer = Offer.new
end

Related

How to call an attribute from a class array

I'm trying to make a method that gets the date and adds onto it an amount of days specified.
At present I cannot call the days specified.
I have a Plant Class that has_many DaysTillSellables, The Period class has_many DaysTillSellable also.
When the user creates a plant they can add a DaysTillSellables and then select a period and then enter an amount of days.
I first need to check to see which period the date is in, then return that period. Currently attempting like so
def current_period
return unless completed_at_week.between?(period.start_week, period.finish_week)
index_days_till_sellables_on_period_id
end
Then Find the days till sellable that is connected to that period and finally call the days from that
Below is the code for the class I'm trying to call it in
class Potting < ApplicationRecord
belongs_to :batch, inverse_of: :pottings
validates :plant_count, :completed_at, presence: true
enum germination_result: { light: 0, medium: 1, full: 2 }
def pottings_completed_at
"Week #{completed_at.strftime('%U').to_i}/#{completed_at.strftime('%Y').to_i}"
end
def completed_at
super || Time.zone.today
end
def completed_at_week
completed_at.strftime('%U')
end
def current_period
return unless completed_at_week.between?(period.start_week, period.finish_week)
index_days_till_sellables_on_period_id
end
def period_days
plant.days_till_sellables.find_by(period: :current_period).&current_period.days
end
def ready_for_sale
completed_at + period_days
end
end
I've added more Code below to give better context for classes
class DaysTillSellable < ApplicationRecord
belongs_to :period, inverse_of: :days_till_sellables, foreign_key: :period_id
belongs_to :plant, inverse_of: :days_till_sellables, foreign_key: :plant_id
validates :days, presence: true
end
.
class Period < ApplicationRecord
has_many :days_till_sellables, dependent: :destroy, inverse_of: :period
belongs_to :organization
.
class Plant < ApplicationRecord
has_many :batches, dependent: :destroy
has_many :goals, dependent: :destroy
has_many :days_till_sellables, dependent: :destroy, inverse_of: :plant
belongs_to :organization
accepts_nested_attributes_for :days_till_sellables, allow_destroy: true
validates :genus, :species, :period_id, presence: true
end
I think you are looking for:
class Potting
belongs_to :plant, through: :batch
...
end

Creating a record using has_many :through?

I have the following models:
class Department < ApplicationRecord
has_many :department_job_titles
has_many :job_titles, through: :department_job_titles
end
class JobTitle < ApplicationRecord
has_and_belongs_to_many :departments
end
class DepartmentJobTitle < ApplicationRecord
belongs_to :department
belongs_to :job_title
validates :department_id, uniqueness: { scope: :job_title_id }
end
This is erring w PG::UndefinedColumn: ERROR: column department_job_titles.title does not exist
LINE 1: ... "department_job_titles"."department_id" = $1 AND "departmen...
Department.first.department_job_titles.find_or_create_by(title: title)
DepartmentJobTitle has the following fields: id, department_id, job_title_id
What am I doing wrong here?
Try this:
job_title = JobTitle.find_or_create_by(title: title)
Department.first.job_titles << job_title unless job_title.in? Department.first.job_titles
Or that second line could be:
Department.first.job_titles = (Department.first.job_titles + [job_title]).uniq
Also:
class JobTitle < ApplicationRecord
has_many :department_job_titles
has_many :departments, through: :department_job_titles
end
... and ...
class DepartmentJobTitle < ApplicationRecord
belongs_to :department
belongs_to :job_title
validates :department, presence: true, uniqueness: { scope: :job_title }
validates :job_title, presence: true
end
... and think about what behaviour you want if someone destroys a JobTitle or Department -- either you want the DepartmentJobTitle destroyed also, or you want the destroy to be prevented, I expect.

Cascade of deletes ActiveRecord

How can add a cascade of deletes that will remove Profile, TodoList, and TodoItem rows for any User removed.
User Model:
class User < ActiveRecord::Base
has_one :profile
has_many :todo_lists
has_many :todo_items, through: :todo_lists, source: :todo_items
validates :username, presence: true
end
Profile Model:
class Profile < ActiveRecord::Base
belongs_to :user
validates :first_name, presence: true
validates :last_name, presence: true
validates :gender, inclusion: %w(male female)
validate :first_and_last
validate :male_Sue
def first_and_last
if (first_name.nil? and last_name.nil?)
errors.add(:base, "Specify a first or a last.")
end
end
def male_Sue
if (first_name == "Sue" and gender == "male")
errors.add(:base, "we are prevent male by name Sue.")
end
end
end
TodoList Model:
class TodoList < ActiveRecord::Base
belongs_to :user
has_many :todo_items, dependent: :destroy
default_scope { order :list_due_date }
end
TodoItem Model:
class TodoItem < ActiveRecord::Base
belongs_to :todo_list
default_scope {order :due_date }
end
Thanks, Michael.
I guess adding dependent: :destroy will do.
#user.rb
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
has_many :todo_lists, dependent: :destroy
has_many :todo_items, through: :todo_lists, source: :todo_items, dependent: :destroy
validates :username, presence: true
end
From the docs:
has_many, has_one and belongs_to associations support the :dependent option. This allows you to specify that associated records should be deleted when the owner is deleted
By using dependent: :destroy on your association in the User class, anytime you destroy a User, all associated objects to that instance gets destroyed as well.
You can check this documentation for more information.

Polymorphic Associations Status in concern

I created concern in which placed association.
I need to make polymorphic association status.
has_one :status, class_name: 'VideoStatus', inverse_of: :video, dependent: :destroy
belongs_to :video, inverse_of: :status
I can't make that Association.How to make it?
require 'active_support/concern'
module EncodeStatuses
extend ActiveSupport::Concern
FORMATS = %w[mp4]
HIGH_VERSION = 'high'
MEDIUM_VERSION = 'medium'
LOW_VERSION = 'low'
VERSIONS = [HIGH_VERSION, MEDIUM_VERSION, LOW_VERSION]
included do
has_one :status, class_name: 'VideoStatus', inverse_of: :video, dependent: :destroy
accepts_nested_attributes_for :status, update_only: true
delegate :success?, :failure?, :waiting?, :encoding?, to: :status
end
end
models/video.rb
class Video < ActiveRecord::Base
include EncodeStatuses
...
end
models/post.rb
class Post < ActiveRecord::Base
include EncodeStatuses
...
end
models/video_status.rb
class VideoStatus < ActiveRecord::Base
STATUS_WAITING = 'waiting'
STATUS_ENCODING = 'encoding'
STATUS_SUCCESS = 'success'
STATUS_FAILURE = 'failure'
STATUSES = [STATUS_WAITING, STATUS_ENCODING, STATUS_SUCCESS, STATUS_FAILURE]
belongs_to :video, inverse_of: :status
belongs_to :post, inverse_of: :status
...
end
has_one :status, as: :video_status, dependent: :destroy
class VideoStatus < ActiveRecord::Base
belongs_to :video_status, polymorphic: true
end

Rails4: Save object with has_many fails on the has_many model validator

I'm trying to save two models (one to many) in one time. My code looks like this:
#submission = Submission.new(submission_params)
#submission_asset = #submission.attachments.new(submission_asset_params)
#submission_asset.attachment_type = 'submission_asset'
if #submission.save
# render or redirect here
else
#submission.errors
end
But when I run this I get this error #messages={:attachments=>["is invalid"]}. I think it's because my attachment model has this:
# Attachment model snippet
validates :attachable_id, :attachable_type, presence: true
But it's to ensure it is attached to a Submission. But when I remove or comment out the validation it works and saves the two models and the association.
How do I make this save?
EDIT
class Submission < ActiveRecord::Base
has_many :attachments, as: :attachable, dependent: :destroy
end
class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
validates :attachable_id, :attachable_type, presence: true
end
#submission_asset = #submission.attachments.build(submission_asset_params)
UPDATE:
class Submission < ActiveRecord::Base
has_many :attachments, as: :attachable, inverse_of: :attachable, dependent: :destroy
end
class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
validates :attachable, presence: true
end

Resources