需要帮助在Rails中创建控制器变量

时间:2013-07-04 14:02:32

标签: ruby-on-rails ruby-on-rails-3

My Rails应用程序允许用户创建描述他们与其他用户关系的“连接”。用户可以评论其他用户的博客帖子(此处称为“作品”),对于博客帖子中的每条评论,我想显示用户与作者的关系。我在工作控制器中创建实例变量时遇到了麻烦。

这是我到目前为止在作品控制器中的show动作中所拥有的:

class WorksController < ApplicationController
def show 
  @work = Work.find(params[:id])
  @workuser = @work.user_id
  @connections = Connection.where(user_id: @workuser, otheruser_id: UNKNOWN).all
  @comment = @work.comments.build
  @comment.user = current_user
  @comments = @work.comments.order("created_at DESC").where(work_id: @work).all 
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @work }
    end
  end
 end

我需要@connections实例变量的帮助,特别是分配otheruser_id:参数的内容。 我知道这需要是发布评论的用户的user_id。但是,我对如何获取此ID感到难过。

以下是模型关系:

work.rb-  belonts_to :user, has_many :comments
user.rb-  has_many :works, has_many :comments, has_many :connections
connection.rb- belongs_to :user

如果我能提供任何其他信息,请告诉我。任何帮助将不胜感激!

谢谢!

编辑:填充评论的视图代码的简化版本(用户,与作者的关系以及评论内容):

<% @comments.each do |comment| %>

  <%= link_to comment.user.full_name, comment.user if comment.user %>,                                                  
  <%= @connections.description %>
  <%= @comment.content %>
   <% end %>

2 个答案:

答案 0 :(得分:1)

请试试

@connections = Connection.where("user_id = ? OR otheruser_id = ?", @workuser, @workuser)

答案 1 :(得分:1)

在您回答我的评论后,我会对实例变量进行更新。但是Bachan的回答应该是双向的。

编辑:

在你谈到单向关系后,我认为你不应该创建@connections实例变量。

而是在user.rb模型中定义一个方法,如下所示:

def get_connection otheruser
 Connection.where(:user_id=>self.id,:otheruser_id=>otheruser.id).first
end

然后在视图中...... 所以你想要显示所有的评论:

  

评论员姓名

     

评论员与作者之间的联系

     

评论内容

好的,你可以这样做:

<% @comments.each do |comment| %>
  <%= link_to comment.user.full_name, comment.user if comment.user %>                                                 
  <%= @work.user.get_connection(comment.user).description unless  @work.user.get_connection(comment.user).nil? %>
  <%= comment.content %>
<% end %>

控制器:

class WorksController < ApplicationController
def show 
  @work = Work.find(params[:id])
  @workuser = @work.user_id
  @comment = @work.comments.build
  @comment.user = current_user
  @comments = @work.comments.order("created_at DESC")
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @work }
    end
  end
 end