ruby-on-railsrubymongoid

How to change model owner in Ruby on Rails?


I use Ruby on rails and mongoid. I have two models User.rb and Project.rb. If I want to change owner of Project model, how should I do this?

User.rb

class User
  include Mongoid::Document

  field :name, type: String
  has_many :projects, dependent: :destroy
end

Project.rb

class Project
  include Mongoid::Document

  field :title, type: String

  validates :user_id, presence: true

  belongs_to :user, touch: true
end

in form.html.erb i have select mode

  <div class="form-group">
    <%= f.collection_select :user_id, User.all, :id, :name, class: 'form-control' %>
  </div>

Solution

  • you should be able to just assign it to the user field and then save it to persist it to the database

    project = Project.find(project_id)
    new_owner = User.find(new_owner_id)
    project.user = new_owner
    project.save