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

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

end

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

Is this the right way?

EDIT1:

In the Project controller I added:

if params[:iit] = 1
    record = GroupPermission.new(cn: 'ccc-ml', project_id: params[:id])
    record.save
end

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?

EDIT2

In the Project Controller

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

private

 def iit_test
   if @trial.iit == 1
   record = GroupPermission.new(cn: 'ccc-ml', project_id: @project.id, name: 'CATEGORY_3')
   record.save
 end

end

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

Thank you in advance.

Answer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *