Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
peteforde opened this issue Jun 5, 2013 · 5 comments
Open

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

peteforde opened this issue Jun 5, 2013 · 5 comments

Comments

@peteforde
Copy link

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
Copy link

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
Copy link
Author

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
Copy link

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
Copy link

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
Copy link

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 🎱

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants