Need to add user_id value to all story table entries

I’m up to page 283 of Simply Rails 2 in the “protective measures” chapter. As the note states, I’m getting errors because now that I’m attempting to reference a user_id, and none exist in previous entries, it is failing…

I thought that I could change all of the story entries in the table by doing the following in the console

Story.find(:all) do |s|
s.user_id=1
s.save
end

but this doesn’t seem to have many any changes.
I can do
s=Story.find(id=6) (id = 6 as an example)
s.user_id=1
s.save

and it’d update the entry accordingly, so I thought it’d work in the block too.

Could somebody tell me if it is possible to get that to work as well in the block to mass change all the entries?

Thanks in advance!

When I run this code in the console I get this error…

NameError: undefined local variable or method `user_id' for #<Object:0x389a0 @controller=#<ApplicationController:0x51fce8>>
        from (irb):28
        from (irb):27:in `each'
        from (irb):27

Any help would be appreciated. I’d rather not do this in SQLite manager :slight_smile:

Typo in kmsolorio solution. It should be:


Story.all.each do |s|
  s.update_attribute(:user_id, 6)
end

That is, user_id needs to be a symbol.

I think adding ids to the fixture YAMLs as I described here:

will also fix this problem.

Heya Reggie,

Thanks for your help in the other thread, this one is a slightly different issue though and not related to testing.

In this particular case, I’ve got a table of stories already, and now a user_id attribute has been added to it. And the view file is calling for the user_id attribute, and thus throwing out errors because the majority of the stories do not already have the user_id value. So I was attempting to set the user_id value of all of the existing stories, but couldn’t get it to work within a block.

I’d just noticed that I’d forgotten to stick my code in a code block, so will do it now.
I tried this within the console, but it didn’t change the values of user_id at all.

Story.find(:all) do |s|
  s.user_id=1
  s.save
end

Again, the other method that I did do (reprinted for the code block), that did work was (the id=6 is just an example). But I didn’t want to do this line-by-line.

s=Story.find(id=6)
s.user_id=1
s.save

Any ideas? Thanks!

PS: I did eventually just worked around it using an if/else clause to ignore the user name display if it s.user_id==nil, but I’m curious now if it is possible to deal with this for future reference.

Kriston, it doesn’t look like you are telling the array to iterate through the block. As it stands, you are creating the array with


Story.all

but to cycle through them you need to add the Array#each method.


Story.all.each do |s|
  s.update_attribute(user_id, 6)
end

Oh. duh.

What a nub mistake. >.<
Thanks for that! :smiley: