0

我不确定如何实例化属于多个对象的对象:

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

基本上一个项目必须属于一个用户。一个项目可以有很多评论(必须属于一个用户),反过来,每个评论可以有很多回复(也必须属于一个用户)。

在我的projects_controller.rb我有以下内容:

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

但是我不知道如何使这项工作。我见过很多关于 Mongoid 模型的例子,但没有这种连接/复杂性。有可能/可取吗?如果没有,有什么替代方案?谁能指出我正确的方向?

非常感谢

4

1 回答 1

0

怎么样@comment = @project.comments.new

您可以使用@project 以评论形式构建评论对象

您可以将 user_id 存储在评论视图中作为隐藏值,例如

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

当您这样做时,@comment = @user.projects.comments.new @user.projects 是数组。

希望它对你有用。

于 2014-11-27T06:25:25.943 回答