reject_if not working

25 views
Skip to first unread message

Eduardo Campestrini

unread,
Oct 29, 2015, 2:59:09 AM10/29/15
to Ruby on Rails: Talk
Hi!

My reject_if filter is not working:

2.2.3 :002 > params = { lead: {name: 'Eduardo', lastName: 'Campestrini', job_attributes: { company: 'RD' } } }
 => {:lead=>{:name=>"Eduardo", :lastName=>"Campestrini", :job_attributes=>{:company=>"RD"}}} 
2.2.3 :003 > lead = Lead.create(params[:lead])
   (0.1ms)  begin transaction
  SQL (1.7ms)  INSERT INTO "leads" ("name", "lastName", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["name", "Eduardo"], ["lastName", "Campestrini"], ["created_at", "2015-10-29 03:35:49.845738"], ["updated_at", "2015-10-29 03:35:49.845738"]]
   (1.2ms)  commit transaction
 => #<Lead id: 11, name: "Eduardo", lastName: "Campestrini", created_at: "2015-10-29 03:35:49", updated_at: "2015-10-29 03:35:49"> 
2.2.3 :004 > 


class Lead < ActiveRecord::Base
  has_one :contact, dependent: :destroy
  has_one :job, dependent: :destroy

  accepts_nested_attributes_for :contact, reject_if: :reject_contact
  accepts_nested_attributes_for :job, reject_if: :reject_job

  validates :name, presence: true, length: { maximum: 50 }
  validates :lastName, presence: true, length: { maximum: 100 }

  private
    def reject_contact(attributes)
      attributes['phone'].blank?
      attributes['website'].blank?
    end

    def reject_job(attributes)
      attributes['company'].blank?
      attributes['title'].blank?
    end
end

class Job < ActiveRecord::Base
  belongs_to :lead
  validates :company, presence: true, length: { maximum: 20 }
  validates :title, presence: true, length: { maximum: 50 }
end


class Contact < ActiveRecord::Base
  belongs_to :lead
  validates :phone, presence: true, length: { maximum: 20 }
  validates :website, presence: true, length: { maximum: 50 }
end

Thank,
Eduardo

Colin Law

unread,
Oct 29, 2015, 3:30:06 AM10/29/15
to Ruby on Rails: Talk

Have you debugged into the code to see what is going wrong? In particular is your filter method being called and if so what is the result?

Colin

Frederick Cheung

unread,
Oct 29, 2015, 7:30:31 AM10/29/15
to Ruby on Rails: Talk
On Thursday, October 29, 2015 at 6:59:09 AM UTC, Eduardo Campestrini wrote:
    def reject_contact(attributes)
      attributes['phone'].blank?
      attributes['website'].blank?
    end


This doesn't do what you want - it's return value depends solely on the blankness of the website attribute. 

Fred

Chaitali Khangar

unread,
Oct 29, 2015, 7:31:13 AM10/29/15
to Ruby on Rails: Talk
 Can you try below solution:

private
    def reject_contact(attributes)
      attributes['phone'].blank? || attributes['website'].blank?
    end

    def reject_job(attributes)
      attributes['company'].blank? || attributes['title'].blank?
    end



Reply all
Reply to author
Forward
0 new messages