开发者

Debug Error in Ruby script

I'm very new to Ruby. I have the following piece of code which is giving me an error.

class ItemsController < ApplicationController
  def populate
    Location.all.each { |l|
      place = l.radar_place 
      next if !place 
      news_items = place.radars
      news_items.each { |ni|
        t = Lbs2.new  
        t.lat = l.lat
        t.lng = l.lng
        t.body = ni.body 
        t.save if !Lbs2.find_by_body(ni.body) 开发者_开发技巧#avoiding redundant news_items
      }
    }
    render :text => "Success"  
  end
end

The error being shown when I hit the url is NoMethodError in ItemsController#populate undefined method `lat=' for Lbs2 id: nil, body: nil, created_at: nil, updated_at: nil

This code worked perfectly without "if !Lbs2.find_by_body(ni.body)" statement. When I included this, in order to avoid the redundant news_items, it gave me the above mentioned error. Can someone please tell me how to get rid of this error at the same time avoiding redundant news_items from getting populated in Lbs2? Thanks in advance


to avoid redundant items i think you can overwrite the validate() method. something like the following:

def validate
   conditions = {"lat" => self.lat, "lng" => self.lng}
   if Lbs2.first(:conditions => conditions)
      errors.add_to_base "Your error message"
   end
end


OK, there are a few things going on here. The error message is saying that it doesn't know how to save something to the "lat" attribute of an Lbs2 object. Even though you told script/generate that you wanted a "lat" field for Lbs2, it looks like it didn't get saved after all. You can check db/schema.rb to be sure. But your first step will probably be to add that field to the appropriate table in the database. Read the Rails Migrations Guide for more info.

Also, there's a much better way to validate uniqueness of a field. In app/models/lbs2.rb (assuming your Lbs2 object is defined there), add a line (outside of any methods) that says:

validates_uniqueness_of :body

Read the Rails Validations Guide for more info.

Hope this helps,
-Jeff T.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜