3

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: 'user@example.com']).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

4

3 回答 3

4

您可以调用valid?对象的单个实例,而不是多个。@contacts意味着您的post_tickets方法正在返回多个对象。

于 2013-08-11T03:26:57.173 回答
2

尝试这样的事情:

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

问题似乎是您添加的方法 dosnt 返回一个活动记录对象,所以该方法有效吗?不可用

编辑:

也许是这样:

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

于 2013-08-11T03:27:14.280 回答
0

天哪,我太笨了,所以我所做的是

  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

它有效!

我仍在努力学习这一切.....感谢您的指导,这真的很有帮助

于 2013-08-11T03:46:38.670 回答