【问题标题】:Rails link_to calls helper method and loads the variables used in modalRails link_to 调用辅助方法并加载模态中使用的变量
【发布时间】:2016-03-17 20:26:17
【问题描述】:

我正在尝试以模式显示评论者的用户个人资料。因此,当用户点击评论上方的“用户名”时,会弹出一个带有相应用户个人资料信息的模式。我尝试将 (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 似乎将我的辅助方法作为路径。当我单击链接“用户名”时,会弹出一个模式,但会显示第一个评论者的个人资料,然后重定向到模式中的 comment_path。我似乎无法在模式中获得正确的用户个人资料信息。

任何建议将不胜感激!

【问题讨论】:

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


    【解决方案1】:

    您的辅助方法不返回用户配置文件,它返回specific_comment

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

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

    顺便说一句,您误用了whereeach。您通过 ID 查找记录,无需使用 where 或遍历结果集。如果您已正确设置关联,您的整个方法应如下所示:

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

    【讨论】:

    • 感谢您的解释。我想我迭代是因为我不明白为什么结果只给了我第一个“评论者”。您的辅助方法很有意义,我在模态中将其用作 。但是,comment.id 似乎没有在模式中更新,我只能获得 first “评论者”的用户个人资料。
    猜你喜欢
    • 1970-01-01
    • 2016-06-01
    • 2011-05-27
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2022-01-18
    • 2011-07-28
    • 2011-08-14
    相关资源
    最近更新 更多