简体   繁体   中英

Why isn't this multi-line console block working in Rails 3?

I'm trying to run this in the Rails 3 console, but when I do, nothing happens. What's wrong with it? Thanks for reading.

Note.find_all_by_user_id(19).each do |a|; a.user_id = 1;a.save; end;

EDIT:

Should have been Note.find_all_by_user_id. I've changed the line above. Same problem occurs though.

Note.find_all_by_user_id(19)
=> [#<Note id: 27, user_id: 19, text: "sample text", created_at: "2010-11-02 15:40:19", updated_at: "2010-11-02 15:40:19">, #<Note id: 28, user_id: 19, text: "sample text", created_at: "2010-11-05 21:40:16", updated_at: "2010-11-05 21:40:16">] 

Note.find_all_by_user_id(19).each do |a|; a.user_id = 1;a.save!; end;
nothing happens

As monocle pointed out, you will not be getting any output here because IRB/Rails console doesn't return anything from blocks called using the "verbose" do/end syntax.

Whatever you do inside the block will still happen, but you won't receive any output from the console. If you really want that, instead of:

Note.find_all_by_user_id(19).each do |a|; a.user_id = 1;a.save; end;

try the curly bracket syntax:

Note.find_all_by_user_id(19).each { |a| a.user_id = 1; a.save }

For more about the "philosophical" difference between curly brackets and do/end, have a look here: http://talklikeaduck.denhaven2.com/2007/10/02/ruby-blocks-do-or-brace

I am trying using Rails 3.0.1 and Ruby 1.9.2

Try to print out the result of the save and see if it is true. Could it be that your user_id needs to be unique? It looks like your user_id is not the primary key of the table... but can it be secondary key? Also try other fields and see if it works.

I think using semicolons like that suppresses the output. Try this

> @x = 0
> [1,2,3].each do |a|; @x += a; end;

I don't get any output. But then

> @x
 => 6

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