user1502223
user1502223

Reputation: 645

ruby on rails - undefined method valid?

im following ryan bates screen cast on how http://railscasts.com/episodes/219-active-model on how to validate a form without a database

but i keep getting an undefined method valid?

heres my controller

def create
  @contacts = FreshDeskApiWrapper.new().post_tickets(params[:contacts])
  if @contacts.valid?
    redirect_to new_contact_path 
  else
   flash[:notice] = "OOps"
   render action: 'new'
 end

end

I can seem to call

 $ FreshDeskApiWrapper.new().valid?

just fine in the console but it does not seem to like it when i tack on the

 $ FreshDeskApiWrapper.new().post_tickets(params[email: '[email protected]']).valid?

i get an undefined method valid?

There is something im not understanding about this

heres my fresh_desk_api_wrapper.rb file i created in my models folder

  class FreshDeskApiWrapper
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :config, :client, :subject, :email, :custom_field_phone_number_50754,      :custom_field_company_50754, :description
  validates :subject, presence: true   
  validates :email, presence: true  
  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i

  def initialize(attributes = {})
    attributes.each do |name, value|
    send("#{name}=", value)
  end
  self.config = YAML.load_file("#{Rails.root}/config/fresh_desk.yml")[Rails.env]
  self.client = Freshdesk.new(config[:url], config[:api_key], config[:password])
  end

  def post_tickets(params)
    client.post_tickets(params)
  end

  def persisted?
    false
  end
end

post_tickets is something im defining in there

Upvotes: 3

Views: 4525

Answers (3)

user1502223
user1502223

Reputation: 645

omg im so dumb so what i did was

  def create

  @contacts = FreshDeskApiWrapper.new(params[:contacts])
  @contacts.post_tickets(params[:contacts])
  if @contacts.valid?
    redirect_to new_contact_path 
  else
   flash[:notice] = "OOps"
   render action: 'new'
  end
end

and it works!

Im still struggling to learn all this.....thanks for your guy's guidance it really helped

Upvotes: 0

Rodrigo Zurek
Rodrigo Zurek

Reputation: 4575

try something like this:

@contacts = FreshDeskApiWrapper.new(post_tickets(params[:contacts])

what seems to be the problem is that the method you are adding dosnt return a active record object, so the method valid? is not available

Edit:

maybe this:

@contacts = FreshDeskApiWrapper.new(FreshDeskApiWrapper.post_tickets(params[:contacts])

Upvotes: 2

sevenseacat
sevenseacat

Reputation: 25029

You can call valid? on an single instance of an object, not multiple. @contacts would imply that your post_tickets method is returning multiple objects.

Upvotes: 4

Related Questions