I'm trying to ask the started_on value of parent in child_model.
I want to compare, if it has the same period
assumed, I have these two classes
class Parent < ActiveRecord::Base
has_many :children
end
And this class, Child_Class:
class Child < ActiveRecord::Base
belongs_to :parent
validates :name, presence: true, :length => { :minimum => 2, :maximum => 50 }
validates :finished_on, presence: true, date: {not_equal: :started_on}
validates :started_on, presence: true, date: {after: :parent.started_on}
end
What I need is the started_on value of parent
:parent.started_on returns me
undefined method 'started_on' for :project:Symbol
And I'm using this validators for my date
Validators
Thanks
class Child < ActiveRecord::Base
belongs_to :parent
validates :name, presence: true, :length => { :minimum => 2, :maximum => 50 }
validates :finished_on, presence: true, date: {not_equal: :started_on}
validate :validate_started_on
private
def validate_started_on
return if parent.nil?
return if started_on > parent.started_on
errors.add :started_on, :should_be_after_the_parent_started_on
end
end
You want to use it without a symbol.
i.e.
parent.started_on
As outlined in the guides
Related
Have many to many relationship but keep getting the same error: ActiveModel::UnknownAttributeError: unknown attribute 'employee_id' for EmployeeSkill. I've checked both my models and it seems like i have IDs for both so not sure what to do?
class Skill < ApplicationRecord
validates :skill_name, presence: true, length: { minimum: 3, maximum: 30}
validates_uniqueness_of :skill_name
has_many :employee_skills
has_many :employees, through: :employee_skills
end
...
class Employee < ApplicationRecord
before_save { self.email = email.downcase }
#validates :email, presence: true, length: { maximum: 30 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_many :employee_skills
has_many :skills, through: :employee_skills
end
...
class EmployeeSkill < ApplicationRecord
belongs_to :employee
belongs_to :skill
end
1) Check if in your migration files and database the corresponding id's are in place.
2) Restart the server (weird but sometimes is needed).
Your code looks good so I think is one of two cases I mention.
Regards,
I am implementing something of a todo list with a user model and a List model with a date attribute.
On the user show page, I retrieve today's to do list.
How do I go about querying a user todo list for the previous and/or the next day.
All insights are welcome, thanks!
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
before_save { self.username = username.downcase }
has_many :to_do_lists, dependent: :destroy
has_many :tasks, dependent: :destroy
validates_presence_of :first_name, :last_name
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
VALID_USERNAME_REGEX = /\A[a-z_0-9]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :username, presence: true,
format: { with: VALID_USERNAME_REGEX },
uniqueness: { case_sensitive: false }
def name
[first_name, last_name].compact.join(' ')
end
end
and the list model
class ToDoList < ActiveRecord::Base
belongs_to :user
has_many :tasks, dependent: :destroy
validates_presence_of :user_id
validates :date, presence: true,
uniqueness: {scope: :user_id}
end
Rails adds many helpful methods to Time to make this type of query quite intuitive. Since you validate that a user has only one to do list for each day:
#next_day_list = #user.to_do_lists.find_by_date(Date.today.tomorrow)
#prev_day_list = #user.to_do_lists.find_by_date(Date.today.yesterday)
I'm working through an API for Rails and have been fumbling how to set up the associations, the spec, and the controller for my Get route. The goal - As a user I want to get all the notes closest to my location that have not been viewed. I know the viewed? logic is off, as is the Query Interface in the Recipients Model and Nearests Controller.
Here's the Error Rspec is giving me:
Failure/Error: note1 = create(:note)
NoMethodError:
undefined method `recipient_id=' for #<Note:0x007fd2a40e1400>
Here's the spec:
describe 'GET /v1/notes/nearests?lat=&lon=&radius=' do
it 'returns the notes within the given radius' do
near_note1 = create(:note, lat: 37.760322, lon: -122.429667)
near_note2 = create(:note, lat: 37.760322, lon: -122.429667)
lat = 37.771098
lon = -122.430782
radius = 10
get "/v1/notes/nearests?lat=#{lat}&lon=#{lon}&radius=#{radius}"
expect(response_json).to eq([
{
'id' => [near_note1.id, near.note2.id],
# 'lat' => near_note1.lat,
# 'lon' => near_note1.lon,
'note_text' => [near_note1.note_text, near_note2.note_text],
'photo_uri' => [near_note1.photo_uri, near_note2.photo.uri],
# 'expiration' => near_note.expiration.as_json,
'viewed' => [near_note1.viewed?, near_note2.viewed?]
},
])
end
end
Here is the controller code:
def index
#notes = Note.near([
params[:recipient_id],
params[:lat],
params[:lon]],
radius: :APP_CONFIG['radius'],
units: :APP_CONFIG['units']
)
end
Here are the Factories - Notes
FactoryGirl.define do
factory :note do |u|
sender_id {FactoryGirl.create(:user).id}
recipient_id {FactoryGirl.create(:user).id}
lat 1.5
lon 1.5
note_text "MyString"
photo_uri "MyString"
expiration Time.zone.now.utc
end
end
My Models:
User Model
class User < ActiveRecord::Base
has_many :notes
validates :first_name, :last_name, :pw, presence: true
validates :email, :username, :devicetoken, presence: true, uniqueness: true
validates :email, length: { minimum: 8 }
end
Note Model
class Note < ActiveRecord::Base
belongs_to :user, foreign_key: 'sender_id', class_name: 'User'
has_many :recipients, foreign_key: 'recipient_id', class_name: 'User'
validates :sender_id, presence: true
validates :lat, presence: true
validates :lon, presence: true
validates :note_text, presence:true
validates :expiration, presence: true
reverse_geocoded_by :lat, :lon
end
Recipients Model
class Recipient < ActiveRecord::Base
belongs_to :note, foreign_key: 'recipient_id', class_name: 'Note'
def get_recipient
Note.find(:all, params[:note_id])
end
def viewed?
end
end
In model I want something like below
validates :category, :presence => true if self.post = "this_is_post"
Is it possible or I have to use a hook method before save for this checking?
This should work:
validates :category, :presence => true, :if => ->(a){ a.post == 'this_is_post' }
Here, more than one code snippest for validate condition in rails:
class Person < ActiveRecord::Base
validates :surname, presence: true, if: "name.nil?"
end
========================
validates :category,
:presence => true,
:if => :valid?
def valid?
self.post == "this_is_post"
end
================
class Person < ActiveRecord::Base
validates :category, presence: true, if: "self.post.eql?('this_is_post')"
end
I want to skip some model validation for controller functions. I am doing like this
Model :
attr_accessible :skip_method_2
validates :name, presence: true, length: { maximum: 50 }, :unless => :skip_method_2
VALID_PHONE_REGEX = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
validates :phoneno, presence: true,uniqueness: { case_sensitive: false, :scope => :user_id}, format: { with: VALID_PHONE_REGEX }, :unless => :skip_method_2
Controller :
def contacts_callback
#contacts = request.env['omnicontacts.contacts']
#contacts.each do |contact|
next if current_user.contacts.exists?(:email => "#{contact[:email]}")
contact1 = current_user.contacts.new(:skip_method_2 => true)
contact1.name = contact[:name]
contact1.email = contact[:email]
contact1.group = "Others"
contact1.save
end
redirect_to "/contact"
end
I dont want to save it by :validation => false. I want to skip name and phoneno validation for contacts_callback function. But it is not working.
It gives error in controller -
undefined local variable or method `skip_method_2' for contacts_callback. I already mentioned attr_accessible in my model
Change validates :name, presence: true, length: { maximum: 50 }, :unless => :skip_method_2
to
validates :name, presence: true, length: { maximum: 50 }, :unless => lambda {|x| x.skip_method_2}
Also checkout this answer