4 ms·
I like using service classes for things like this. class StoryService def self.assign_story(params) story = Story.find(params[:story_id]) use
by dan_manges 15y ago
I like using service classes for things like this.
class StoryService
def self.assign_story(params)
story = Story.find(params[:story_id])
user = User.find(params[:user_id])
story.assign_to(user)
end
end
This example is fairly minimal, but with service classes handling workflow and object coordination instead of the controller, the code is easier to test and reuse.
- rhizome 15y agoSee, this strikes me as CS-driven code smell. Why not use an association between User and Story (maybe through :assignments) and just `user.stories.create(...)` or `user.assignments.create(:story => story)` ? No spurious class necessary.
- dan_manges 15y agoThat is probably how you would do it in this case, but in more complex scenarios, a simple association wouldn't be sufficient. In those cases, putting the code into a service instead of the controller will make the code easier to test and reuse.