I have products and brands
products model:
class Product < ActiveRecord::Base
attr_accessible :brand_id, :title
belongs_to :brand
validates :title, :presence => true
validates :brand, :presence => {:message => 'The brand no exists'}
end
and the brands model
class Brand < ActiveRecord::Base
attr_accessible :name
validates :name, :presence => true
has_many :products, :dependent => :destroy
end
I want to validate if exist a product with a name in this brand.
I mean I could have 2 products with the same name in different brands but not in the same brand.
You could use the uniqueness validation with a scope:
validates :name, :uniqueness => { :scope => :brand_id }
Note that you have to specify :brand_id instead of :brand, because the validation can't be made on the relation.
If you don't know it, I suggest you to read the Active Record Validations and Callbacks guide.
NB: the syntax {:foo => 'bar'} is replaced (since Ruby 1.9.2) with {foo: 'bar'}.
Related
I'm pretty new to the whole rails MVC concept, and I've been tasked with creating a form which does the following:
takes a test number
shows how many sections there are per test (this is a constant, always 4)
allows a region for the user to enter in their responses for each question in a section. The number of questions in each section changes depending on the test number they get.
I have my view which looks like this:
= form_for [#answer_sheet] do |f|
=f.collection_select(:test_prep_number, Exam.find(:all),:test_prep_number, :test_prep_number, {:include_blank => 'Select your test prep number'})
=f.fields_for :answer_sections do |section_form|
=section_form.label :section
.form-inline
=f.label :A
=radio_button_tag 'answer', 'A'
=f.label :B
=radio_button_tag 'answer', 'B'
=f.label :C
=radio_button_tag 'answer', 'C'
=f.label :D
=radio_button_tag 'answer', 'D'
=f.label :E
=radio_button_tag 'answer', 'E'
My controller looks like this:
def index
#answer_sheet = AnswerSheet.build_with_answer_sections
#answer_section = AnswerSection.new
#section_count = AnswerSection.where("exam_id = ?", params[:test_prep_number).count
end
The issue I'm having right now is I can't seem to wrap my head around creating the correct number of radio buttons. So far, I've managed to generate only one question per section.
I'm assuming I'll need a for loop (which will then require a query to find how many questions per exam section).
Edit: Adding models as requested
Answer sheet model
class AnswerSheet < ActiveRecord::Base
attr_accessible :date, :raw_score, :test_prep_number, :answer_sections, answer_sections_attributes
MAX = 101
validates :test_prep_number, :presence => true
validates :raw_score, :presence => true, :numericality => { :greater_than_or_equal_to => 0, :less_than_or_equal_to => MAX}
validates :date, :timeliness => {:on_or_before => lambda { Date.current }, :type => :date}, :presence => true
belongs_to :user
has_many :answer_sections
Answer Section model
class AnswerSection < ActiveRecord::Base
MAX = 30
attr_accessible :section_score, :answers, :answer_attributes
has_many :answers, :dependent => :destroy
belongs_to :answer_sheet
accepts_nested_attributes_for :answers
validates :section_score, :presence => true, :numericality => { :greater_than_or_equal_to => 0,
:less_than_or_equal_to => MAX }
I would recommend tweaking your models to something the breaks the choice from the users answer:
class Test < ActiveRecord::Base
belongs_to :user
has_many :question
attr_accessible :date, :test_prep_number
validates :test_prep_number, :presence => true
validates :date, :timeliness => {:on_or_before => lambda { Date.current }, :type => :date}, :presence => true
end
class Question < ActiveRecord::Base
MAX = 30
attr_accessible :question_text
has_many :choices, :dependent => :destroy
has_one :answer
belongs_to :test
accepts_nested_attributes_for :answers
end
class Choice < ActiveRecord::Base
attr_accessible :question_id, :choice_text, :correct_choice
belongs_to :question
end
class Answer < ActiveRecord::Base
attr_accessible :choice_id
belongs_to :user
belongs_to :question
end
I have the following model in rails (simplified):
class Phone < ActiveRecord::Base
include ActiveModel::Validations
belongs_to :user
belongs_to :brand
attr_readonly :user, :brand
attr_accessible :model, :phone_number
validates :user, :presence => true
validates :brand, :presence => true
validates :model, :presence => true
validates :phone_number, :presence => true
end
According to the documentation, attr_readonly should allow attributes to be set at creation, but not at update.
However, when I do this:
Phone.create(:user => <existing_user>, :brand => <existing_brand>, :model => "Galaxy", :phone_number => "555-433-5678")
I get this error:
Can't mass-assign protected attributes user, brand
What am I missing?
If you want to assign a user and a brand association like that, you must define them as being accessible attributes:
attr_accessible :user, :brand
Otherwise, you can assign them like this:
Model.create({:user => user, :brand => brand }, :without_protection => true)
I have a model Competitor like this
class Competitor < ActiveRecord::Base
belongs_to :admin_user
has_many :companies
attr_accessible :admin_user_id, :c1, :c2, :c3, :c4, :c5
validates :admin_user_id, :presence => true
validates_uniqueness_of :admin_user_id, :message => "This user has yet a competitors list"
end
C1, c2,.. are the id of companies. Selected from a drop down list. How can I validate the uniqueness of a row?
(i.e. is not possible to have two or more equals companies for an admin user BUT they can be empties).
You could write your own validation method that would enforce this.
class Competitor < ActiveRecord::Base
belongs_to :admin_user
has_many :companies
attr_accessible :admin_user_id, :c1, :c2, :c3, :c4, :c5
validates :admin_user_id, :presence => true
validates_uniqueness_of :admin_user_id, :message => "This user has yet a competitors list"
validate :check_companies
def check_companies
#[do your checks]
end
end
Following is my models:
class Poll < ActiveRecord::Base
attr_accessible :published, :title
validates :published, :presence => true
validates :title, :presence => true,
:length => { :minimum => 10 }
has_many :choice, :dependent => :destroy
end
class Choice < ActiveRecord::Base
belongs_to :poll
attr_accessible :choice_text, :votes
validates :choice_text, :presence => true
end
I then tried to install the rails admin. I was able to create the choices and polls in the admin, but i was unable to associate a choice with a poll and vice versa.
How can i do it?
First of all in has_many class name should be in plural:
has_many :choices
And you should add attr_accessible poll_id or choice_ids for Model from which you want to edit this association. Or just delete all attr_accessible for first try.
class Poll < ActiveRecord::Base
attr_accessible :published, :title, choice_ids
validates :published, :presence => true
validates :title, :presence => true, :length => { :minimum => 10 }
has_many :choices, :dependent => :destroy
end
class Choice < ActiveRecord::Base
belongs_to :poll
attr_accessible :choice_text, :votes, :poll_id
validates :choice_text, :presence => true
end
There is no attr_accessible in Rails 4. Use accepts_nested_attributes_for instead. More info:
https://github.com/sferik/rails_admin/wiki/Belongs-to-association
Model Code (Attempting to require uniqueness for embed_code)
https://gist.github.com/1427851:
class Link < ActiveRecord::Base
validates :embed_code,
:format => {:with => /^<object type|^<embed src|^<object width|^<iframe src|^<object height|^<iframe width|^<embed id|^<embed width|^<object data|^<div|^<object id/i, :message => "Invalid Input"},
:uniqueness => true
attr_accessible :title, :embed_code, :score
after_initialize :calculate_score, :favs_count
attr_accessor :score, :fav_count
validates :title, :length => { :in => 4..45, :message => "Must be between 4 & 45 characters"}
before_save :resize
has_many :favorites
has_many :favorited, :through => :favorites, :source => :user
belongs_to :user
I've tried validates_uniqueness_of :embed_code and disabling (commenting out) non-critical components of the model such as :before_save :resize