how to render rails form by jquery?

天涯浪子 提交于 2019-12-13 20:09:40

问题


I am trying to render follow and unfollow forms into rails view

Create.js.erb ( my problem is here as this is wrong code only acts on CSS not the rails forms and I can't seem to handle it D:)

$('.btn-danger').attr('class', 'btn')
                   .val('Following')
                   .attr('id', 'btn-unfollow');

destroy.js.erb ( also this is wrong code only acts on CSS, not the rails forms )

$('.btn').attr('class', 'btn-danger')
                   .val('unfollowed')
                   .attr('id', 'btn-follow');

my Postsindex.html.erb

<% @posts.each do |f| %>
<%= f.headline %>
<%- f.text %> 
    <% if current_user.id != f.user.id %>
    <% if !current_user.following?(f.user) %>
    <%= form_for(current_user.active_relationships.build, remote: true) do |s| %>
      <div> <%= hidden_field_tag :followed_id, f.user.id %> </div>
      <%= s.button "follow", class: "btn btn-danger", id: "follow-btn" %>
      <% end %>
      <% else %>
      <%= form_for(current_user.active_relationships.find_by(followed_id: f.user.id), :html => {method: :delete}, remote: true) do |s| %>
      <%= s.button "unfollow", class: "btn", id: "unfollow-btn", remote: true %>
      <% end %>
      <% end %>
      <% end %>

<% end %>

posts controller :

class PostsController < ApplicationController
 def new
    @post = Post.new
  end
def index
@posts = post.all
end
end

The only problem is that follow and unfollow are not on partials but rather on same page so if i can render each of them separatley I will be thankful ...


回答1:


I would do something like below for your situation. Hope you'll find that solution helpful too.

  1. Create a separate controller followersController. It'll handle the all follow/unfollow related activities. (I believe you've created a model too)
  2. Try to respond the view with :js in controller
  3. So, If someone hits follow button then the controller > create method will be hit. After create change the view by rendering a js file named create.js.erb and write appropriate code.
  4. When someone hits unfollow button then the controller > destroy method will be hit. After create change the view by rendering a js file named destroy.js.erb and write appropriate code.
  5. In view, try to use different id in the follow/unfollow button so that in the js file you can handle the selectors easily.

In the create.js.erb file, you should do something like that:

$('#follow_button_parent_div').html("<%=j render partial: 'unfollow_button_html_file' %>")

in _unfollow_button_html_file.html.erb, write a <form></form> with unfollow button as submit to destroy the recently created follow record.

for destroy section, modify codes accordingly.




回答2:


I would do something like this. Please change to adapt to your models and fields in your database

Posts view: I would make two links to follow or unfollow. Only one is visible (depending on the author of the post and if I am already following him). These links would make a ajax post to follow/unfollow the author of the post and will switch links (hides himself and shows the other link)

<% @posts.each do |post| %>
  <%= post.headline %>
  <%- post.text %> 
  <% if current_user.id != post.user.id %>
    <%= render partial: 'follow_links', locals: { user: post.user }
  <% end %>
<% end %>

Partial follow_links.

<% show_follow_link   = current_user.following?(user) ? 'hidden' : '' %>
<% show_unfollow_link = current_user.following?(user) ? '' : 'hidden' %>

<!-- links to follow/unfollow have data-attributes that include the path to make the ajax post and the user to follow, that is used to find the link to show after the ajax call -->
<%= link_to 'Follow',   '#', { class: 'follow-user btn-success #{show_follow_link}', "data-url": follow_user_path(user.id), "data-followee": user.id } %>
<%= link_to 'Unfollow', '#', { class: 'unfollow-user btn-danger #{show_unfollow_link}', "data-url": unfollow_user_path(user.id), "data-followee": user.id } %>

Javascript for the partial

$('.follow-user').on("click",function() {
  target = $(this)
  url = target.attr('data-url')
  followee = target.attr('data-followee')
  other_button = $('.unfollow-user[data-followee="'+followee+'"]')

  $.ajax( {
    url: url,
    type: 'post',
    success: function() {
      target.addClass('hidden');
      other_button.removeClass('hidden');
    },
    error: function(ret) {
      alert(ret.responseJSON.error);
    }
  });

});

$('.unfollow-user').on("click",function() {
  target = $(this)
  url = target.attr('data-url')
  followee = target.attr('data-followee')
  other_button = $('.follow-user[data-followee="'+followee+'"]')

  $.ajax( {
    url: url,
    type: 'post',
    success: function() {
      target.addClass('hidden');
      other_button.removeClass('hidden');
    },
    error: function(ret) {
      alert(ret.responseJSON.error);
    }
  });

UsersController (new methods to follow and unfollow)

def follow
  if !current_user
    render json: { :error => 'You must log in' }, :status => :unprocessable_entity
    return
  end

  who_to_follow = User.find_by id: params[:id]
  if !who_to_follow
    render json: { :error => 'User not found' }, :status => :not_found
    return
  end

  # Change user_id by the field in the relationship that links to the followee
  followee = current_user.active_relationships.create(user_id: who_to_follow.id)
  render json: who_to_follow, :status => :ok
  return
end


def unfollow

  if !current_user
    render json: { :error => 'You must log in' }, :status => :unprocessable_entity
    return
  end

  who_to_unfollow = User.find_by id: params[:id]
  if !who_to_unfollow
    render json: { :error => 'User not found' }, :status => :not_found
    return
  end

  # Change user_id by the field in the relationship that links to the followee
  unfollowee = current_user.active_relationships.find_by user_id: who_to_unfollow.id

  if !unfollowee
    render json: { :error => 'You are not  following this user' }, :status => :unprocessable_entity
    return
  end

  unfollowee.destroy
  render json: who_to_unfollow, :status => :ok
  return

end

Add routes

post  "/users/:id/follow"    => 'users#follow',   :as => :follow_user
post  "/users/:id/unfollow"  => 'users#unfollow', :as => :unfollow_user


来源:https://stackoverflow.com/questions/48728366/how-to-render-rails-form-by-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!