I have model Order:
class Order < ActiveRecord::Base
has_one :shipping_address
has_and_belongs_to_many :books
validates :first_name, :surename, :email, :street1, :country, :zipcode, presence: true
validates_format_of :email, :with => /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
validates :zipcode, numericality: true
accepts_nested_attributes_for :shipping_address
end
and model Book:
class Book < ActiveRecord::Base
DEFAULT_PRICE = 55.15
NEXT_BOOK_PERCENT = 5
has_and_belongs_to_many :pages
has_and_belongs_to_many :orders
validates :name, presence: {message: "Name can't be blank."}
validates_length_of :name, minimum: 3, maximum: 12, message: "Sorry, we can't create this book right now. Please contact us for further information."
validate :same_letter_validation
validate :validates_for_non_alphabetic
before_save :compile
#......
end
Also I have table books_orders (book_id, order_id)
When I try do delete order from RailsAdmin panel I get next error:
NoMethodError in RailsAdmin::Main#delete
undefined method `orders_books' for #
It says that error in this line:
- #abstract_model.each_associated_children(object) do |association, child|
Have you defined that "orders_books" method anywhere in your code? If so, can you please add it to your question. If you haven't, then the root cause of your issue is just that, that you're calling the "orders_books" method but it is not yet defined
Given that you reference "#books_orders" in your question, I believe it likely that you just swapped "books_orders" and "orders_books" at some point in your code
Thanks. It's bug of a Rails 4.1.1. I have update it to 4.1.4 and all works OK.
Related
I have a mode named Exam.
There are some columns in exames:
:title
:subject_id
:exam_type
I want to know how to implement this:
class Exam < ApplicationRecord
validates :title, presence: true
validates :subject_id, presence: true, if: :no_exam_type?
def no_exam_type?
self.exam_type == ""
end
end
That is to say, I want to create a exam:
Exam.create(title: "first exam", exam_type: "something")
The subject_id must be exist, when exam_type is blank, such as exam_type="" or just do:
Exam.create(title: "first exam", subject_id: 3)
because exam_type has a default blank value.
But the subject_id doesn't necessary provide, when exam_type not blank, such as exam_type="something".
Exam.create(title: "first exam", exam_type: "something", subject_id: 3)
I test it, but no lucky.
How to do that? Thanks appreciate.
In Rails 5 belongs_to associations default to optional: false. Which means that the model will automatically validate the presence of the association.
class Thing < ApplicationRecord
belongs_to :other_thing
end
Thing.create!
# => ActiveRecord::RecordInvalid: Validation failed: other_thing can't be blank
So you need to set the association as optional and make sure the column is nullable.
class Exam < ApplicationRecord
belongs_to :subject, optional: true
validates :title, presence: true
validates :subject_id, presence: true, if: :no_exam_type?
def no_exam_type?
!self.exam_type.present?
end
end
Have you tried like this.
validates :subject_id, presence: true, :if => exam_type.blank?
you can refer the doc here to suite your requirement
use validates_presence_of instead.
validates_presence_of :subject_id, if: :no_exam_type?
def no_exam_type?
self.exam_type.nil?
end
I have a JavaScript to mask a value in my form. I'm trying to remove this mask before save it in db, but i have problems
model:
class Partner < ApplicationRecord
belongs_to :address, dependent: :destroy
has_many :dependents
accepts_nested_attributes_for :address
# Validations #
# Validates presence of some attributes #
validates_presence_of :registry_number, :name, :secretary, :position, :base_salary, :rg, :cpf, :birthday, :email, :union_admission, :start_date
validates :registry_number, numericality: {only_integer: true}
# Validates the size of some attributes #
validates :registry_number, length: {maximum: 5}
validates :cpf, length: {is: 11}
validates :rg, length: {is: 9}
validates :phone_number, length: {maximum: 11}
:cpf.gsub(/[.\/]/, '')
end
error
undefined method `gsub' for :cpf:Symbol
Extracted source (around line #18):
16
17
18
19
20
:cpf.gsub(/[.\/]/, '')
end
How can I solve it?
As the error message tells you, the line :cpf.gsub(/[.\/]/, '') is the problem. Firstly, you're calling the method gsub on a symbol :cpf, and the method doesn't exist . Try it in irb.
Secondly, even if this wasn't the case, it wouldn't make any difference – the code is only going to be run once when the class is loaded and wouldn't be run each time you save a new Partner. You need to add a before_validation callback to run your code each time you create a new object, which would look something like this:
class Partner
#...
before_validation :unmask_cpf
#...
private
def unmask_cpf
cpf = cpf.gsub(/[.\/]/, '')
end
end
gsub is a method on strings, so you can call .to_s on the symbol first.
Real newb question here: I've got courses
class Course < ActiveRecord::Base
attr_accessible :name, :number
has_many :posts
validates :name, presence: true
validates :number, presence: true
validates :number, :format => { :with => /\A\d\d[-]?\d\d\d\z/}
end
and I've got posts
class Post < ActiveRecord::Base
attr_accessible :comments, :course_id, :difficulty, :enjoyability, :hours, :professor, :ranking, :semester, :usefulness
belongs_to :course
end
Almost everything I have was auto-generated by Rails. There are a couple of things I try to do that I can't get to work:
When I "show" a course, I want to show each post associated with that course. However, everything I've tried has given me an error.
After even entering one post into the database (heroku forced me to use PostgreSQL) the index form no longer renders.
I'm almost positive I'm missing something with my associations between them. Does anybody have any ideas as to what I'm doing wrong?
You may get all posts through Course instance:
#course = Course.find(params[:id])
#posts = #course.posts
Model order.rb
class Order < ActiveRecord::Base
attr_accessible :address, :email, :name, :payment_type_id
belongs_to :payment_type
PAYMENT_TYPES = PaymentType.pluck(:id)
validates :name, :address, :email, :payment_type_id, :presence => true
validates :payment_type_id, :inclusion => {:in => PAYMENT_TYPES}
end
Model payment_type.rb
class PaymentType < ActiveRecord::Base
attr_accessible :name, :id
has_many :order
end
From browser, validation works fine, if it is wrong it give an error, else go forward.
But problem is when I run rake test:functionals from terminal. Test didn't pass the validation. If I comment this line:
validates :payment_type_id, :inclusion => {:in => PAYMENT_TYPES}
all is ok. I don't understand why it is working in one plase, but in tests not ? ...
Fixtures are all ok.
Please help.
Most likely the problem is, that you are storing your payment types in a constant.
For your tests to work, the PaymentTypes have to be available in the database before rails loads your Order model, and this might not be the case.
One way to get around this, would be to use a (memoized) class method to store your payment types. As long as you access this class method after all your PaymentTypes are in the database, you should be fine.
class Order < ActiveRecord::Base
validates :payment_type_id, :inclusion => { :in => self.payment_types }
def self.payment_types
##payment_types ||= PaymentType.pluck(:id)
end
end
In many of my rails models, I have a number of fields which are what I think of as "normal" model attributes, ie things which are set by the user, then later displayed, and are mandatory parts of a model instance. It seems kind of overly verbose to have to always do this:
class Person < ActiveRecord::Base
attr_accessible :name
attr_accessible :age
attr_accessible :height
validates :name, :presence => true
validates :age, :presence => true
validates :height, :presence => true
end
Ideally I'd like to just tell rails "everything but the auto-generated ID field should be validated present and accessible for mass assignment". How can I do that, given that it's said to be bad security practice to just make everything available for mass assignment?
Update: The existing way also seems bad in that I type my list of attributes twice, which is quite error prone.
Define your own class method, say on ActiveRecord::Base:
class ActiveRecord::Base
def self.validate_presence_and_make_accessible *args
attr_accessible *args
validates_presence_of *args
end
end
Then in your models:
class Person < ActiveRecord::Base
validate_presence_and_make_accessible :name, :age, :height
end
I suck at naming methods sometime, btw. Feel free to rename to something better.
A little less verbose way:
class Person < ActiveRecord::Base
attr_accessible :name, :age, :height
validates :name, :age, :height, :presence => true
end
Specifying only protected attributes:
class Person < ActiveRecord::Base
attr_protected :id
validates :name, :age, :height, :presence => true
end
This is simpler:
class Person < ActiveRecord::Base
attr_protected :id
validates_presence_of :name, :age, :height
end
And regarding your comment about security practice of mass assignments, I think you should read this: http://b.lesseverything.com/2008/3/11/use-attr_protected-or-we-will-hack-you