RailsApps / rails3-bootstrap-devise-cancan

Outdated. See the rails-devise-pundit example app for Rails 4.1.
http://railsapps.github.io
491 stars 207 forks source link

Rails 4: Role.find_or_create_by_name in db/seeds.rb #40

Open peteforde opened 11 years ago

peteforde commented 11 years ago

The example seed file suggested fails under Rails 4 RC1 with the following error and a stack trace:

Could not find table 'name'

I converted:

Role.find_or_create_by_name({ :name => role }, :without_protection => true)

to:

Role.where(:name => role).first_or_create(:without_protection => true)

Now it seems to work great.

Note that I did switch from find_or_create to first_or_create, which seemed more explicit for this context.

kirstywilliams commented 11 years ago

Your suggestion cleared my "Could not find table 'name'" error, however now I am stuck getting a unknown attribute: without_protection error.

Any suggestions? Rails noob here!

Setup: Rails 4.0 Ruby 2.0.0p0 rolify, devise, cancan (all latest versions)

peteforde commented 11 years ago

Hi @kirstywilliams!

Technically it is "rails3" so it might have been better to try this running against Rails 3. Is that possible for you at this point?

If not, I'll try and help you through this. Could you paste the full error you're getting? It's hard to guess what's happening without a bit more context.

Pete

kirstywilliams commented 11 years ago

Thank you for your reply. I got it to work with Rails 4.0. I didn't include the attr_accessible suggested instead opting for Rails 4.0 strong parameters this is what caused my problem. I have since included the protected attributes gem along with the attr_accessible and all is good :)

Kirsty

schadenfred commented 11 years ago

Kirsten if you are new it's probably better to skip using the protected attributes gem and protect against mass assignment using the rails 4 way. It's my favorite thing about rails 4. To see how it works just look at the user controller code on a new rails 4 app when you do rails g scaffold user name email password. The protection happens a before action filter defined at the bottom of the file. Good luck!

joelhooks commented 11 years ago
YAML.load(ENV['ROLES']).each do |role|
  puts role
  Role.where(name: role).first_or_create
  #Role.find_or_create_by_name({ :name => role }, :without_protection => true)
  puts 'role: ' << role
end

This was my solution. find_or_create_by_ has been deprecated. It works with the email ones though, so I don't know. I'm a noob :8ball: