Which part of Rails should take care of updating chained model statuses? - ruby-on-rails

I have 2 models
ShippingClass, which define a shipping fare and the destinations to which the shipping fare is applicable
Shop, which has a state machine that determine if a number of actions are allowed or not
A shop has_many shipping_classes. The user can add or delete shipping classes and, among other factors, the fact that at least one shipping_class exist or not has an impact on the shop state.
The bottom line is that any time a shipping class is added/deleted/modified I run an update_state method on the shop model to keep the state up to date. What this method does is basically checking how many shipping_classes are associated to the shop and adjust the shop status accordingly (eg, to simplify the shop state is active if there is at least 1 shipping_class assigned, otherwise is inactive)
I was wondering if it is good practice to update the shop state from the controller. I am in fact evaluating the opportunity of having the ShippingClass to update the Shop upon save and destroy. While this may be more error proof, as I don't need to remember to update the Shop model every time I save a ShippingClass, it however increases the coupling of the models.
Using callbacks to do this appears not to be an option. These are wrapped into transaction.
Therefore the parent model (Shop) does not see exactly what is the status of the associated models (ShippingClasses) before the transaction is completed.
EDIT
Another option, as pointed out below, is to place the model update into an observer. The advantage of this is that it is not wrapped into a transaction, so the Shop model should be able to check the associated ShippingClasses. The disadvantage is that is not wrapped into a transaction, so a failure to update the Shop model would desync the Shop status. This would, however be better than placing the update into the controller, as it would be done once forever.
Another option could be override the save and destroy methods of ShippingClass and update the Shop model from there.
What is the best practice and why?
THanks in advance

As you pointed out, keeping the logic in the model is best since it will then apply any time a controller attempts to modify/delete/add a ShippingClass. Within the model, I would look to use a callback on ShippingClass - have the ShippingClass update the state of any Shops that are affected as a result of the modify/delete/add operation.

Related

Rails: Working on (Updating) 2 different controllers at the same time

I want to implement a simple discount coupon. I have a model that valid coupons are saved (beside some other things) and a Product model that product features are stored (name, price, ...).
I have a simple form that enables the user to enter his coupon. I should check it to see if it is valid or not (I defined a scope for it). If the entered coupon is valid, I have to update both of the mentioned tables. In the first one, I have to change the coupon to "used" and in the second table, I should update the price with the new value. And I want to do these operations when the user entered a value in the form.
What is your suggestion and solution to do both of them? As these two operations are related to 2 different models and controllers, I cannot access them in one controller. What is the best way to call a method to do these operations? Could you please give me a clear explanation?
You have access to both models in either controller however to do this the "rails way" you should put this logic in your model. I would add a before_update callback in your coupon model that checks if the coupon is being changed to "used" as you mention. If so, you can then update its "price" in your product table. The key concept to takeaway from this is that you can call all Models from anywhere and they are not limited to their respective controllers only.

Where should I place the score variable when allocating a score to a Model/Object in Ruby/Ruby on Rails?

I have a model in my Rails app for a SalesOpportunity, and running a SWOT analysis (Strength, Weakness, Opportunity, Threat) to decide how good the SalesOpportunity is. Swots belong_to SalesOpportunities and therefore in the SalesOpportunity Model I have a method called update_swot_score which iterates through the Swot objects and calculates a score based on parameters I'm feeding in. All of this works fine.
What I'm wondering is whether I need to add a field to my SalesOpportunity model (let's call it swot_score for simplicity) and to update the instance variable at the end of the update_swot_score method using #swot_score = "results of my calculation", or whether I can directly access a result of the update_swot_score method (ideally in my view - I'll display different partials depending on the result).
What is the Rails way of doing this? Is there a performance efficiency to be gained by using either method?
i will suggest to add in the db as a dedicated column to store score...there are few good reasons as why you should do it:-
dedicated column to store only score
easily maintainable even you decide to add/edit new score type in future
Can be called/updated/modified anywhere throughout your application
can use callbacks in future as well(on_create,on_update) as its in a Model
Performance wise,its awesome as you can cache it..can also counter_cache and expire too.
Hope it helps

Rails validations: update at the same time as creation

I'm having some trouble trying to figure out how to order ActiveRecord writes to make my validations be happy, and I'm not sure what to search for this kind of problem.
The problem is that before the request would occur, everything would be valid; after the transformations would occur, everything would be valid again; but while the transformation is happening, since it's impacting more than one model instance, the database would enter an invalid state if I update each model one by one without taking into account both changes at the same time. I'd love some suggestions!
Background
I have a model called HelpRequest and another called HelperAssignments.
The rule is that a HelpRequest may have 0 or 1 active HelperAssignments. But if a Helper cannot complete the request, they may reassign it to another Helper, creating a new HelperAssignment. Since we need the history of assignments to a particular HelpRequest, there may be a number of HelperAssignments for a HelpRequest, but only one is active.
As a result, the HelperAssignment table has a few relevant attributes:
help_request_id: Refers to the HelpRequest corresponding to this assignment.
close_status: If this is set to reassigned, reassignment_id must be present.
reassignment_id: For a given help_request_id, only one may be nil (i.e. it is the current active assignment)
Problem
When a reassignment happens...
... if I create the new HelperAssignment first, it would break validations because more than one active HelperAssignment for the request would be present :(
... if I update the old HelperAssignment first to have a close_status of reassigned, the new HelperAssignment wouldn't exist yet so I couldn't get its ID, and therefore the validations would fail.
Is there an idiomatic way to do this transformation? I'd like to avoid a) disabling validations for this particular type of requests, or b) adding an extra database state for "being in the process of reassigning". Looks like enforcing referential integrity in models can get a little tricky in Rails... thanks in advance!

has_many :through model names, controller and attributes best practices?

Disclaimer: I really spent time thinking about names of models and variables. If you also do, this question is for you.
I have a Rails project which contains two models: User and Project.
They are connected by the model ProjectsUser, which is a connection model in a many-to-many relationship. This model also holds the role of a user in the given project, along with other attributes such as tier and departments. So this is a has_many :through relationship.
Given this scenario, here is everything that always bothered me on all my rails projects since I started developing on it:
Should I use a ProjectsUserController or better add the relevant actions on UserController and ProjectController? At some point, I want to assign users to a project, or even changing the role of a user in a given project. Is it a better practice to leave those actions on the connection controller, or use the model controllers?
Should I write a method to get the role of a user for a given project? This is basically if I should have a method User#role_for(project) or not. Since this method basically is getting the information from the projects_user object it could make more sense to always let this explicity on the code, since most of the times I'll have the project and the user, but not the projects_user. Is this line of thinking correct, or maybe the problem is that I'm should have more project_user on my code than I really do? Are there good caveats for this?
Should I try to rename my table to a non-standard name if it is not obvious? Ok, I got that if I have the models User and NewsSite I should use has_many :subscriptions, but the thing is that naming those models in real life cases are usually harder, by my experience. When the name ends up not being that obvious (for exemple, in my case, maybe project_participation as #wonderingtomato suggested) is for the best, or in those cases it is better to fall back to the ProjectsUser approach?
One extra cookie for pointing beautiful open source Rails code, or by book indications that might help with my kind of questions.
I would use a specific controller. Even if now the interaction sounds simple, you can't know if in the future you'll need to add more advanced features.
I've been handling these kind of relationships in several projects, and using a controller for the join model has always paid off.
You can structure it this way, for example:
index should expect a params[:project_id], so that you can display only the index of users for a specific project.
create is where you add new users, that is where you create new join models.
update is to modify a value on an existing join model, for example when you want to update the role of a user in a project.
destroy is where you remove users from the project, that is where you delete the corresponding join models.
You might not need a show and edit actions, if you decide to manage everything in the index view.
Also, I'd suggest to choose a different name. Rails relies heavily on naming conventions, and projects_users is the default name for the join_table you would use with a has_and_belongs_to_many association. In theory you can use it for an independent model (and a has_many through:), but it's not immediately clear and you might break something. In addiction, it will confuse the hell out of any new programmer that could join the project in the future (personal experience).
What about calling the model something like project_participation?
If you haven't built a lot of functionality yet, and don't have yet that table in production, changing it now will save you a lot of headaches in the future.
update
1) I stand by what I said earlier: your join model is a full fledged record, it holds state, can be fetched, modified (by the user) and destroyed.
A dedicated controller is the way to go. Also, this controller should handle all the operations that modify the join model, that is that alter its properties.
2) You can define User#role_for(project), just remember that it should properly handle the situation where the user is not participating to the project.
You can also make it explicit with something like:
#user.project_participations.where(project_id: #project.id).first.try(:role)
# or...
ProjectParticipation.find_by(project_id: #project.id, user_id: #user.id).try(:role)
But I'd say that encapsulating this logic in a method (on one of the two models) would be better.
3) You are already using a non standard name for your table. What I mean is that it's the default name for a different kind of association (has_and_belongs_to_many), not the one you are using (has_many through:).
Ask yourself this: is the table backing an actual model? If yes, that model represents something in the real world, and thus should have an appropriate name. If, on the other hand, the table is not backing a model (e.g. it's a join table), then you should combine the names of the tables (models) it's joining.
In my mind, REST doesn't always have to map directly to DB records. A conceptual resource here is the association of Projects to Users. Implementation would be different depending on your persistence layer, but a RESTful API would be standard.
Convention over Configuration in Rails is a great helper, but it isn't necessarily applicable to every case 100% of the way through the stack. There doesn't need to be a 1-to-1 mapping between controllers, models, and their respective names. At the app-level, particularly, I want my routes/controllers to represent the public view of the API, not the internal implementation details of the persistence and domain layers.
You might have a UserProjectsController which you can perform CRUD on to add/remove project associations to users, and it will do the appropriate record manipulation without being overly bound to the DB implementation. Note the naming, where the route might be /user/:id/projects, so it's clear you are manipulating not Users or Projects, but their associations.
I think thinking about this sort of thing (both before and after the fact) is what leads to better designs.
I too start with the model and think about the application structurally. The next step in my oppinion is to build the user interface to make sense based on what makes it easy and useful for the user (spending more effort on things that matter more). So if it makes sense for the user to separately edit the ProjectsUser objects then the ProjectsUsersController is the way to go. More likely editing the join model objects as part of the Project (or User depending on the structure of you app) will be a better fit for the user. In that case using a nested form and editing via the controller (and model) that's the main model referenced by the form is better. The controller really lives to serve the UI, so decisions about it should be dependent on the UI.
Yes, if it makes your code simpler or more readable. If you use role more than once I suspect it will.
I would actually name that model something like Member, or ProjectMember (or Membership). It defines a relationship between a user and a project, so its name should reflect what relationship that is. In the occasions where such a name is too unwieldly or too hard to define then falling back to something like ProjectUser is reasonable (but not ProjectsUser). But I definitely like finding a more meaningful name when possible.

Ruby on Rails: When to add a new resource

I have two questions on how the MVC works. I'm pretty sure I should add several resources, but I'm just coming to this conclusion and wanted to ask first to get a better understanding.
First question:
I have two models, user and subject. Users can enter subjects into the database. For each subject there are 5 data entry forms (Baseline, 3month, 6month,...) that are about 100-200 questions each (The relationship would be each subject has 1 of each data entry form). Should each data entry form be a new resource?
Second Question:
Lets say I want to randomize a few subjects into a group:
From the view, the user enters the amount of subjects to be randomized into a group, as well as the group name to be assigned. The form tag specifies an action I created, just for this function, called randomize.
From the controller, randomize uses the params sent from the view to query the database, and then to update each record to reflect the group. Instead of creating a new action for the randomize function, should I create a new resource for it? And as a side note, should any of these calculations be done in the model (other than defining the variables)?
Thank you for your time. Any help would be greatly appreciated. I am officially over-whelmed by all of the information I'm learning about this...but I feel that I'm really close to actually understanding the MVC.
I'll answer your second question first.
You should be creating controllers to handle CRUD tasks for resources. In this question you ask about creating a "Group". Regardless of whether this is an actual resource, or just a modification to a collection of other resources, you have the concept of creating a "Group", probably reading/updating a "group" and certainly deleting one.
Based on this, I would rather have a RandomGroup controller which I can call using a standard REST interface, rather than some #randomize action stuffed in the side of another controller.
As for your first question ... maybe, maybe not.
It really depends on whether an data entry form has any business logic of its own. If it doesn't then there's no harm it being part of a large object. But if your tests and code start to become too complex within the Subject model you may want to split it out into multiple models or at least multiple modules included into that model.
Perhaps you could consider that "Baseline", "3month", "6month" are all the same ... aside from their lead time. Perhaps that is a model in itself, and Subject could has_many :forms ??
Food for thought.

Resources