teresa
teresa

Reputation: 366

Rails link_to calls helper method and loads the variables used in modal

I'm trying to show the user profile of commenters in a modal. So when the user clicks on the "username" above the comment made, a modal pops-up with the appropriate user profile info. I try to pass in (comment.id) parameter to my helper method, then return the user profile for each commenter, which I use in my modal view.

My helper:

def getuserprofileofcommenter(commentid) 

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

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

end 

My modal (in view):

<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>
...

My view:

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

The link_to seems to be taking my helper method as a path. When I click on the link "username", a modal pops-up but with the first commenter's profile and then redirects to comment_path in the modal. I can't seem to get the correct user profile info in the modal.

Any advice would be greatly appreciated!

Upvotes: 0

Views: 304

Answers (1)

user229044
user229044

Reputation: 239301

Your helper method doesn't return a user profile, it returns a specific_comment.

The last statement in the method is its return value. The fact that you assign to @commenter is completely irrelevant.

Your last statement is specific_comment.where(...), and the result of that statement is specific_comment itself. If you want to return the user (or "commenter") for the comment, you need to actually return it, not just assign it to an instance variable.

As an aside, you're misusing where and each. You're finding a record by ID, there is no need to use where or iterate over a result set. If you've set up your associations correctly, your entire method should look like this:

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

Upvotes: 0

Related Questions