scopes should be in controller or model? - ruby

I am new to ruby and rails development and have this question in mind. If i have a concern with scope created say latest_records which gives me latest data for a customer
Now what is the best practice to use scope in this situation. should scopes be in model or in controller?
I read some online articles and it talks about fat model and skinny controller and since scopes are do database related work then i am guessing they should be in model.
Any suggestions or thoughts?

You guessed it right.
Scopes belong to model and needs active record classs object to work on.
Scopes are nothing but a activerecord query divided in parts and it helps look your query elegant and dry.
e.g.
If you want to get users with confirmed emails, you would:
User.where(confirmed: true)
But with scopes in your user model:
scope :confirmed, -> { where(confirmed: true) }
And you would simply:
User.confirmed
For more detailed please refer this answer here

A scope could only be defined in a model so it would have to be on a model.

Related

Restricting access to a model in Laravel

I'm building a small little CRM type app for my brother's company as a Laravel learning exercise. I really like what I've learned from this framework so far.
I have a Deal model that has a couple of boolean attributes, for_management and for_admin. My User model also has is_management and is_admin boolean attributes.
My main route to show the deals right now is returning all deals, but of course I want to only show the deals that are relevant to the user. A user might be both management and admin, so not sure of the best way to structure that logic.
Feels like I don't really want that logic to exist in the controller and might be better being defined in the User?
Scopes are another thing I've been looking at, but it doesn't feel like it would be "the right thing".
What would you suggest?

Laravel Eloquent Relationships methods syntax

everyone:
I'm trying to create an application with several many to many relations, including a m-m rel onto the same model. It's a headache. In the official docs there is no so much information. I've been looking the code for belongsToMany method, in HasRelationShips.php, but there are not description on the parameters use.
Where can I get detailed documentation about the use of the parameters, in order to learn the right way to create any kind of relationships?
Do you know any book or document which details the working of all of the methods and parameters, so I can read it and REALLY learn how do they work?
Thanks everyone
Bro, in the DOCs you can find it easily.
Belongs to Many is like that:
public function companys(){
return $this->belongsToMany('App\Users', 'companys_users', 'user_id', 'company_id')->withTimestamps();
}
https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

Can i use instances of a laravel model instead of facades?

I'm wondering whether it is possible/advisable to use instances of a laravel model instead of using the Facade. Why all this trouble? I have a model which will be used with many tables, and i want to be setting the model's table automatically using the constructor. Is it possible/advisable, or what is the best approach of achieving the same end?
I have researched around with no much success.
UPDATE
THis is the scenario: an exam system, where different exams are "created". after an exam is created, a table is created in the database under the name Exam_#, where # is the ID of the exam. I want to access all exam from one model: Exam, but you see the particular table the model is to use can vary significantly, so we cannot set the table variable statically. The model shall not know the table it will use until it(the model) is called. So thats why i was wondering whether i can be passing the ID of the exam when i am calling the model or something like that. I hope my question is now more clear.
At the end of this, Laravel is still PHP... Anything you can do in PHP can be done in Laravel.
is (it) possible/advisable to use instances of a laravel model instead of using the Facade?
You can achieve exactly the same results using an instance of the model as you would using the static facade.
$user = User::find(1);
$user2 = new User();
$user2 = $user2->find(1);
Both instances of the above model contain the same results.
Is it advisable? I really don't like the static facades at all, they bring with them more trouble than they are worth, especially when it comes to testing (despite being able to mock them, they create tight coupling where most of us need loose coupling). My answer to this would be: don't use the facades at all.
What is the best approach of achieving the same end?
As #JoelHinz suggested, create a base model with common properties and then use the models as they are intended. i.e. ONE table to ONE model and create the relationships between them. Don't use the same model for multiple tables, this is not how Laravel models were intended and you will lose a lot of the power Eloquent provides by taking the approach you mentioned.
Updates from comments
To get you started with testing in Laravel this is a good end to end tutorial Tutsplus Laravel4 + Backbone. Ignore the backbone part, what you're interested in is the testing parts that start about a 1/3rd of the way down the page. This will get you testing controllers straight away and introduce you to the repository pattern to create testable DAL structures.
Once you get the hang of writing tests, it becomes very easy to write a unit test for anything. It may seem like a scary subject, but that is purely down to not understanding how it works, it really is quite simple. Take a look at the PHPUnit documentation as well, it is an excellent resource.

Zend Framework User Authentication (MVC question)

I'm getting some trouble understanding the MVC concepts.
I'm building a User model, you know? Application_Model_Users. They say that the models should only contain the structure... and the business logic should be put in the controller.
So, consider a function called authenticate($user, $password). This function will return true if the username and password entered is valid or false otherwise. Where should I put this function? In the controller Authentication or in the model Users?
Thank you!
Related to the Model, whenever you need to retrieve data(from DB, Web service, filesystem) or save data, you need a model to do the job. In MVC, a model is not understood as a mapped table, maybe more like a mapper. Zend has some info about this at their site, it could help you understanding mvc a bit more.
When it comes to user authentication, you should certainly implement the authenticate function inside the Users model, I would think you will do a database check against a table or similar.
Just in case you are not already using it, Zend comes with a package for auhtentication: Zend_Auth (http://framework.zend.com/manual/en/zend.auth.html) , it could speed up implementing the security at your application.
Although Model operations often include storage operations (DB, servicer, etc), it is not limited to that. Model, as far as I know, should countain Business logic entities, this is, classes that represent your business entities, like User, Person, Customer, etc. Each class should define its own operation methods, in example, a Person model class should allow you to get a person's name, calculate his/her age according to his/her birth date, etc.
Also, there should be specialized classes for Model storage and retrieval. With these classes you could fetch all your Customers, or only one, using certain conditions, etc, or save a modified Customer class instance (in example, a customer changed his/her address or phone number).
This separates the storage/retrieval operations from Business login operations.
So, according to your question, your model could have a class that allows you to find one user by its user name and password. If the user is found, you could return a Model_User class instance (in example). Then, using the standard Zend_Auth class, or extending it to create your own authentication class, you can use some Login form parameters to perform the user authentication.
Follow the Zend Framework quick start guide, there are the basics about MVC in Zend Framework. Also, there you will find some resources about Zend_Db and related classes, to allow DB interaction. There are also Zend_Db_Table, Zend_Db_Table_Rowset and Zend_Db_Table_Row classes, that you could extend to fit your model storage needs.
I have a personal solution where I extend Zend_Db_Table for my (in example) Model_UserTable class, used to store or query my Model_User entities. And my Model_User class extends Zend_Db_Table_Row.

Best practices for implementing models in the MVC pattern

What are the best practices for implementing models in the MVC pattern. Specifically, if I have "Users" do I need to implement 2 classes. One to manage all the users and one to manage a single user. So something like "Users" and "User"?
I'm writing a Zend Framework app in php but this is more a general question.
The model should be driven by the needs of the problem. So if you need to handle multiple users, then a class representing a collection of Users might be appropriate, yes. However, if you don't need it, don't write it! You may find that a simple array of User objects is sufficient for your purposes.
That's going to be application and MVC implementation specific. You might well define a class collecting logically related classes, or you could define a static register on the user class. This is more of an OO question than MVC.
I'll second Giraffe by saying the use of included collections is almost always better than trying to write your own.
But I think your original question could be reworded a little differently... "Do I need a separate class to manage users other than the User class?
I use a static factory class to build all of my users and save them back to the database again. I'm of the opinion that your model classes need to be as dumbed down as possible and that you use heavy controller classes to do all of the work to the model classes.

Resources