avram
avram copied to clipboard
Make it easier to set default associations in a Factory
Depends on #331
class ArticleBox < Box
def initialize
post { PostBox.create }
end
# This is auto-generated by the box. Putting it here just to show rough implementation
def post
before_save do
if post_id.value.blank?
record_or_id = yield
id = if record_or_id.is_a?(Avram::Model)
record_or_id.id
else
record_or_id
end
post_id id
end
end
end
end
This will most likely require changes to https://github.com/luckyframework/avram/blob/master/src/avram/save_operation.cr so that we have access to an ASSOCIATIONS
constant that has a list of associations and the column to use.
Relevant examples:
- https://github.com/luckyframework/avram/blob/bb576790a832b41db10ccf8087fa9a43934a9b6f/src/avram/save_operation_template.cr#L43
- https://github.com/luckyframework/avram/blob/d67dd63936e2276f603819076f1c391ea4076cab/src/avram/save_operation.cr#L80-L82
We'd want to add a add_association_attributes
or something. This will be a bit more complex so I'll try to tackle it, but if someone else wants to take a stab at it, post here and I'll try to help if you run into anything
I'm looking into this
Thanks for looking into this @matthewmcgarvey!
This is basically how it works now
class PostFactory < Avram::Factory
def initialize
before_save do
if operation.user_id.value.nil?
user(UserFactory.create)
end
end
end
def user(u : User)
user_id(u.id)
end
end
PostFactory.create
I'd imagine this could look like
class PostFactory < Avram::Factory
belongs_to user : UserFactory
end
The tricky part might be if this is just a macro that ends up making an initialize, how do you handle when an initialize is defined by the user? :thinking: