Search code examples
ruby-on-railsrubyviewcontrollerhotwire-rails

Controller processing with HTML in rails


I set a turbo_frame_tag at profile/follow_button like

<%= turbo_frame_tag "#{dom_id(@user)} follow_user" do %>
  <% if following?(user) %>
    <%= link_to "Unfollow", profile_unfollow_path(id: user.id), method: :delete, class: "" %>
  <% else %>
    <%= link_to "Follow", profile_follow_path(id: user.id), method: :post, class: "" %>
  <% end %>
<% end %>

and i want hotwire load the acction Unfollow, Follow when click this so i set this in my controller

def follow
    Relationship.create_or_find_by(follower_id: current_user.id, followee_id: @user.id)
    # redirect_back(fallback_location: root_path)
    respond_to do |format|
      format.turbo_stream do
        render turbo_stream: update_action_follow
      end
    end
  end


  def unfollow
    current_user.followed_user.where(follower_id: current_user.id, followee_id: @user.id).destroy_all
    # redirect_back(fallback_location: root_path)
    respond_to do |format|
      format.turbo_stream do
        render turbo_stream: update_action_follow
      end
    end
  end


  private
  def update_action_follow
    private_target = "#{dom_id_for_follower(@user)} follow_user"
    turbo_stream.replace(private_target,
                         partial: 'profile/follow_button',
                         locals: {
                           user: @user
                         })
  end

  def update_count_follower
    private_target = "#{@user.id}-follower-count"
    turbo_stream.update(private_target,
                        partial: 'profile/follower_count',
                        locals: { user: @user
                        })
  end


normally the format will be TURBO_STREAM, but when I check under the log it's HTML enter image description here

so i got the problem like enter image description here

how can i fix this?


Solution

  • I got the solution by myself, just specific turbo_method in link_to like

     <% if following?(user) %>
        <%= link_to "Unfollow", profile_unfollow_path(id: user.id), class: "",data: { turbo_method: :delete } %>
      <% else %>
        <%= link_to "Follow", profile_follow_path(id: user.id), class: "",data: { turbo_method: :post }%>
      <% end %>
    

    This is needed because I am using Rails 7 with Turbo.