seed_dump icon indicating copy to clipboard operation
seed_dump copied to clipboard

Is Active Record Associations supported?

Open r4do opened this issue 8 years ago • 2 comments

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.

r4do avatar Apr 04 '16 11:04 r4do

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().

GarthSnyder avatar May 08 '16 23:05 GarthSnyder

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

yovasx2 avatar Nov 03 '16 19:11 yovasx2