Ruby on Rails DB entry in a model (RoR 3) Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Ruby on Rails DB entry in a model (RoR 3) without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Skip to EDIT2 which works

There is:

  • Project (has_many :group_permissions)
  • GroupPermission (belongs_to :project)

I have a form where you can create a new project. A project has several attributes like name, status etc. and now important: iit. iit is selectable with radio buttons: yes or no.

What I want:

If someone selects yes on iit in the Project form, there should be a new record in GroupPermission. So in EVERY project where iit= 1 there should be a certain GroupPermisson.

Can I make / check this in the GroupPermission model? Like if

class GroupPermission < ActiveRecord::Base
    if Project.where(iit: 1)
     make me a record for each project


Can I even make database entries in the model like so?

Is this the right way?


In the Project controller I added:

if params[:iit] = 1
    record = 'ccc-ml', project_id: params[:id])

It then adds a new record in GroupPermissions. But I need the :id of the project. How can I access the id of the project which is about to be saved?


In the Project Controller

after_filter :iit_test, :only => [:create]


 def iit_test
   if @trial.iit == 1
   record = 'ccc-ml', project_id:, name: 'CATEGORY_3')


EDIT2 works fine. I just have to check it with update etc.

Thank you in advance.


the EDIT2 will only work for apis hitting the controller and not when you add a project via rails console, use in tests etc.

Also this :iit_test will not correctly work for update action as you are creating a new GroupPermission everytime. (GroupPermission may already exists for this project)

You should probably add a callback after_save in the project model and handle adding of a new GroupPermission there.

We are here to answer your question about Ruby on Rails DB entry in a model (RoR 3) - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji