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

Make it easier to set default associations in a Factory #385

Open
paulcsmith opened this issue Jun 9, 2020 · 3 comments · May be fixed by #950
Open

Make it easier to set default associations in a Factory #385

paulcsmith opened this issue Jun 9, 2020 · 3 comments · May be fixed by #950

Comments

@paulcsmith
Copy link
Member

paulcsmith commented Jun 9, 2020

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:

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

@matthewmcgarvey
Copy link
Member

I'm looking into this

@paulcsmith
Copy link
Member Author

Thanks for looking into this @matthewmcgarvey!

@jwoertink jwoertink changed the title Make it easier to set default associations in a box Make it easier to set default associations in a Factory Jul 15, 2022
@jwoertink
Copy link
Member

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? 🤔

@jwoertink jwoertink added the Hacktoberfest Valid Issue for Hacktoberfest label Oct 1, 2022
@jwoertink jwoertink removed the Hacktoberfest Valid Issue for Hacktoberfest label Nov 6, 2022
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

Successfully merging a pull request may close this issue.

3 participants