rroblak / seed_dump

Rails 4/5 task to dump your data to db/seeds.rb
MIT License
1.39k stars 225 forks source link

Is Active Record Associations supported? #97

Open r4do opened 8 years ago

r4do commented 8 years ago

Hi! If I want to get some model, and all records, belonging to it, how can I do this? For example, I have User model, and UserAction model (User has_many :user_actions and UserAction belongs_to :user). I want to get 100 UserAction random copies, and all Users belonging to them, but no other users. Thank you.

GarthSnyder commented 8 years ago

Try this:

actions = UserAction.order("rand()").limit(100) users = actions.map(&:user).uniq SeedDump.dump(users, ...) SeedDump.dump(users, append: true, ...)

The rand() part is for MySQL; I believe other databases use random().

yovasx2 commented 7 years ago

In rails 5 it's not because of belongs_to is required, I get this:

Comment.create!([
  {text: "qqq", post_id: 1}
])
Post.create!([
  {title: "aa", text: "aa"}
])

And of course this error:

➜  blog rails db:seed   
rails aborted!
ActiveRecord::RecordInvalid: Validation failed: Post must exist
/Users/galberto/blog/db/seeds.rb:1:in `<top (required)>'
/Users/galberto/blog/bin/rails:9:in `require'
/Users/galberto/blog/bin/rails:9:in `<top (required)>'
/Users/galberto/blog/bin/spring:14:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)

But check this out http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html