Question

I want to display fort each user a list of the ongoing conversations. So they can just click on it and display the conversation they want. I have trouble to find how to make this link, since the conversation object in mailboxer don't have an id.

This id seems to be stored in the notification object, so I tried this option.

This code come from the conversation index view

<%all_conv = current_user.mailbox.conversations%>
<%all_conv.each do |participant|%>
  <div class="ligne_conversation">
  <ul>
    <a href="conversations/<%=@conversation_id%>">
      <li>
        <%=image_tag participant.messages.last.sender.avatar.url(:thumb) %>
        <%=participant.messages.last.sender.name%>                  
        <%=participant.messages.last.body%>
      </li>
    </a>
  </ul></div>

The @conversation_id instance variable is define in my conversation controller

def index
  if current_user.mailbox.conversations.any?
  notification = Notification.find_by!(params[:id])
  @conversation_id = notification.conversation_id
  end
end

It's not working : all links lead to the conversation with id = 1.

Was it helpful?

Solution

I assume that if someone clicks on a conversation link it will go to your conversation controller and look for def show and not def index. Therefore you need to have something like:

    def show
       @conversation = Conversation.find(params[:id])
      respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @conversation }
     end
    end

In your index controller you need to do:

    def index
       @conversations = current_user.mailbox.conversations

Lastly in your view you iterate over @conversations like

    @conversations.each do |c|
     <a href="conversations/<%= c.id %>

You might want to look up link_to and url_for to make it all more elegant but the above will work.

Here a very simple advice for the start into your Rails adventure:

Create a new rails app:

    rails new learncrud
    cd learncrud
    rails g scaffold thing name body something:int
    rake db:migrate
    rails s 

then go to 127.0.0.1:3000/things and look at the result

When done open the app in your favorite text editor and look how the scaffolder has created the pages and controller actions. Maybe you have done it, maybe not, but it sure helps to get a very quick grasp of how things can be done in rails. Hardcoding controller names in a href is sure not the best way of doing things.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top