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

Already on GitHub? Sign in to your account

Simpler association syntax #100

wants to merge 1 commit into


None yet
3 participants

szimek commented Nov 28, 2010


I've simplified syntax for defining associations, so it's no longer necessary to explicitly use #association method. One can now do:

factory :post do
  author :factory => :user, :first_name => "Ben"

I'm not 100% sure if the test is correct, but I tried to make it similar to the other ones :)


szimek commented Nov 28, 2010

I'm not sure if the check for :factory key is really necessary - skipping it would allow to override association attributes without using #associate method as well.

wycats commented Nov 28, 2010

Question: is it possible to allow the first parameter to just be a Symbol? Something like:

factory :post do
  author :user, :first_name => "Ben"

Or is the Symbol type already taken for some reason?


szimek commented Nov 29, 2010

Passing 2 attributes is actually a good idea (otherwise factory_girl doesn't really know if "author" is just an attribute and you're assigning a hash to it, or if it's an association), although there are 2 small issues with it:

  • you can't use this syntax to override a single attribute of the association like when using #association method
  • it would differ from the syntax of #association method, where :factory option is used

Maybe this "syntax sugar" could be added to factory_girl_rails gem? We could check there if given attribute is actually an association via #reflect_on_association and handle it accordingly.


joshuaclayton commented Jun 30, 2011

We'll definitely look into this, as I think it's a bit more intuitive and I really dig not having to declare every association "longhand" if it doesn't use its named factory. We're getting ready to cut a 2.0 release, but it's something I'd like to get in shortly. Thanks!


joshuaclayton commented Jul 29, 2011

@szimek, could you rebase against our upstream changes for a clean merge? I'm interested in getting this in soon; thanks!

Simplify association syntax when defining new factory.
Now it's possible to do:

factory :post do
  author :factory => :user

szimek commented Jul 30, 2011


BTW. Would it be possible to further simplify this syntax as wycats suggested by adding some code to factory_girl_rails gem to check if an attribute is an association via association reflections?


joshuaclayton commented Jul 30, 2011

I'd be interested in seeing that pull request. My concern is that it wouldn't work for non-ActiveRecord, which would be confusing I think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment