Rails link_to调用helper方法并加载modal中使用的变量

时间:2016-03-17 20:26:18

标签: ruby-on-rails twitter-bootstrap bootstrap-modal helper link-to

我试图在模态中显示评论者的用户个人资料。因此,当用户点击"用户名"在评论上方,弹出一个带有相应用户个人资料信息的模态弹出窗口。我尝试将(comment.id)参数传递给我的帮助器方法,然后返回每个评论者的用户配置文件,我在模态视图中使用它。

我的帮手:

def getuserprofileofcommenter(commentid) 

  specific_comment = Comment.where("id = ?", commentid)

  specific_comment.each do |comment|
    @commenter = Userprofile.find_by("id = ?", comment.userprofile_id)
  end

end 

我的模态(在视图中):

<div id="commenterModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
...
  <div class="row">
    <div class="col-sm-9">
          <p style="font-weight: bold;"><%= @commenter.user_description %></p>
          <p><%= @commenter.bio %></p>
    </div>
  </div>

<div class="modal-footer">
  <button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">OK</button>
</div>
...

我的观点:

<%= link_to "username", getuserprofileofcommenter(comment.id), :class => "btn", :remote => false, "data-toggle" => "modal", "data-target" => "#commenterModal" %>

link_to似乎将我的帮助方法作为路径。当我点击链接&#34;用户名&#34;时,会弹出一个模式,但会弹出第一个评论者的个人资料,然后重定向到模态中的comment_path。我似乎无法在模式中获得正确的用户个人资料信息。

非常感谢任何建议!

1 个答案:

答案 0 :(得分:0)

您的帮助方法不会返回用户个人资料,而是返回specific_comment

方法中的最后一个语句是它的返回值。您分配给@commenter这一事实完全无关紧要。

您的上一个语句是specific_comment.where(...),该语句的结果是specific_comment本身。如果要返回注释的用户(或“评论者”),则需要实际返回,而不是仅将其分配给实例变量。

顺便说一句,你误导了whereeach。您正在按ID查找记录,无需使用where或迭代结果集。如果您已正确设置关联,则整个方法应如下所示:

def getuserprofileofcommenter(commentid) 
  Comment.find(commentid).userprofile
end