开发者

Adding to an array in Ruby on Rails

I'm currently writing a ruby function that gets a table from a database and then based on the data creates an array. It's written like this:

  def listSome
    @foos = Array.new
    FooTable.find(:all) do |foo|
      @foos << foo if foo.name == "Bar"
    end
  end
开发者_运维百科

The problem I'm having is that only the first element of the query is getting added to the array. I've checked that FooTable.find(:all) returns what I think it should in the console and also that it's ok to loop off of it's results (I printed the results on every loop, it found what it was looking for). I suspect, however, there is something about concatenation to arrays/collections that I don't understand. Why am I only getting the first result of the query added into my array? Thanks.


You are providing a block to the find method which isn't going to run it against each element of the array it returns. Provide your block to the each method returned by find.

FooTable.find(:all).each { |foo| ... }

Also, assuming this is actual code and not an example, there is a really bad way of getting foos with a specific name.

rails 2

@foos = FooTable.find(:all, :conditions => ['name = ?', 'Bar'])

rails 3

@foos = FooTable.where('name = ?', 'Bar')


You forgot the each: FooTable.find(:all).each do |foo|.

But I'd make some more comments, you should use more map/select/reject/inject and less each:

def listSome
  @foos = FooTable.find(:all).select do |foo|
    foo.name == "Bar"
  end
end

But whenever possible, use more SQL and less Ruby:

def listSome
  @foos = FooTable.where(:name => "Bar")
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜