Has_many: through model names, controllers, and best practice attributes?

Disclaimer: I really thought a lot about model names and variables. If you do, this question will be for you.

I have a Rails project that contains two models: Userand Project.

They are connected by a model ProjectsUser, which is a many-to-many relationship model. This model also contains the roleuser in this project along with other attributes, such as tierand departments. So this is the attitude has_many :through.

Given this scenario, here is all that has always bothered me on all my rails projects since I started to develop it:

  • Should I use ProjectsUserControlleror better add appropriate actions on UserControllerandProjectController ? At some point, I want to assign users to the project or even change the role of the user in this project. Is it better to leave these actions on the connection controller or use model controllers?

  • Do I have to write a method to get the user role for this project? This is mainly if I have to have a method User#role_for(project)or not. Since this method mainly receives information from the object projects_user, it may make more sense to always allow this explication in the code, since most of the time I will have Projectand User, but not projects_user. Is this line of thinking right, or maybe the problem is that I should have more project_useron my code than I really do? Are there any good reservations for this?

  • , ? , , User NewsSite has_many :subscriptions, , , , . (, , , project_participation @wonderingtomato), ProjectsUser?

cookie Rails , .

+4
3

. , , .
, .

, :

  • index params[:project_id], .
  • create - , , .
  • update , , .
  • destroy - , , .
  • , show edit, index.

, . , projects_users - join_table, has_and_belongs_to_many. ( has_many through:), , - . , , ( ).

project_participation?

, .

1) , : - , , , () . . , , , .

2) User#role_for(project), , , user project.

- :

@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)

, ( ) .

3) . , (has_and_belongs_to_many), , (has_many through:).
: , ? , - , , . , , (, ), (), .

+4

, REST DB. . , API RESTful .

Rails - , 100% . 1 1 , . , , , / API, .

UserProjectsController, CRUD / , . , /user/:id/projects, , .

+1

, ( , ) - , .

  • . , , ( , ). , ProjectUser, ProjectUsersController - . , ( ) . ( ), , , . , , .

  • , . , , .

  • - Member ProjectMember ( Membership). , , . , , - ProjectUser ( ProjectUser). , .

+1

Source: https://habr.com/ru/post/1527131/


All Articles