简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM