AaronLasseigne / active_interaction

:briefcase: Manage application specific business logic.
MIT License
2.06k stars 136 forks source link

Q: How do I dealing with Association (has_many / nested-fields)? #527

Closed Kowa1229 closed 2 years ago

Kowa1229 commented 2 years ago

For example now I got a table User, with associations has_many task.

In my User Model,

class User < ActiveRecord::Base has_many :tasks end

And my Task Model,

class Task < ActiveRecord::Base belongs_to :user end

So I'm trying to do something with active_interaction gem.

I can validate my User model well, but however I not sure how do I work with my has_many relations. Not sure how do I passed in the tasks_attributes.

I've tried to specify my tasks_attributes as example belows:

array :task_attributes do object class: "Task" end

Or even hash, but it doesn't go through, and the things I wanted to passed in "task_attributes" is a type for "ActionController ::Parameters".

Also I wanted to find some ways to validate the has_many association under my "CreateUser" activeinteraction file.

Looking for suggestion:

  1. How to pass in has_many attributes into an activeinteraction file?
  2. How to validate model (User) -> has_many association (Task) attributes? And how do I return the errors?
AaronLasseigne commented 2 years ago

It sounds like you want to pass in an array of task attributes. Let's say that a task has two attributes, title and completed_by. It would look something like this:

array :task_attributes do
  hash do
    string :title
    date :completed_by
  end
end

From there you can see if the tasks are valid and add the errors to :base if you want them to bubble up. It would look something like this:

def execute
  ...
  tasks = task_attributes.map { |attrs| Task.build(attrs) }
  tasks.each do |task|
    errors.merge!(task.errors) unless task.valid?
  end
  ...
end