Search code examples
ruby-on-railsruby-on-rails-4mongoid4

How instantiate a Mongoid model with multiple belongs_to


I'm not sure how to instantiate an object that belongs to multiple objects:

class Project
    ...
    belongs_to      :project_lead,      :class_name => 'User'
    has_many        :users,             :class_name => 'User'
    has_many        :comments
end

class Comment
    ...
    belongs_to      :author,        :class_name => 'User',      inverse_of: :comments
    belongs_to      :project,       :class_name => 'Project',   inverse_of: :projects
    embeds_many     :replies,       :class_name => 'Reply'
end

class User
    ...
    has_many    :comments,      :class_name => 'Comment',   inverse_of: :author
    has_many    :projects,      :class_name => 'Project',   inverse_of: :project_lead
    has_many    :replies,       :class_name => 'Reply'
end

class Reply
    ...
    belongs_to  :author,    :class_name 'User'
    embedded_in :comment
end

Basically a project must belong to a user. A project can have many comments (which must belong to an user) and in turn, each comment can have many replies (which must also belong to an user).

In my projects_controller.rb I have the following:

def new
    @user = current_user #that works fine
    @project = @user.projects.new # works fine
    @comment = @user.projects.comments.new #doens't work
end

However I don't know how to make this work. I've seen many examples with Mongoid models but nothing with this sort connection/complexity. Is it possible/adivisable? If not, what's the alternative? Can anyone point me in the right direction?

Many thanks


Solution

  • how about @comment = @project.comments.new

    Either you can build comment object with @project in comment form

    You can store user_id in comments view as hidden value like

    #comments/_form.html.erb
     <%= form_for([@project, @project.comments.build]) do |f| %>
         <%= f.hidden_field :user_id, value: current_user.id %>
    

    When you do @comment = @user.projects.comments.new @user.projects is array.

    hope it will work for you.