【发布时间】:2018-02-12 04:50:28
【问题描述】:
我正在尝试将关注和取消关注表单呈现到 Rails 视图中
Create.js.erb(我的问题在这里,因为这是错误的代码只作用于 CSS 而不是 rails 表单,我似乎无法处理它 D:)
$('.btn-danger').attr('class', 'btn')
.val('Following')
.attr('id', 'btn-unfollow');
destroy.js.erb(这也是错误的代码只作用于 CSS,而不是 rails 表单)
$('.btn').attr('class', 'btn-danger')
.val('unfollowed')
.attr('id', 'btn-follow');
我的 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 %>
帖子控制器:
class PostsController < ApplicationController
def new
@post = Post.new
end
def index
@posts = post.all
end
end
唯一的问题是关注和取消关注不是在局部,而是在同一页面上,所以如果我可以单独渲染它们,我将不胜感激......
【问题讨论】:
-
不是一个答案,但是为什么你在每个帖子都叫'f',然后你把表格叫's'?除此之外,我不明白这个问题。为什么你使用表单而不是简单的链接?这只是一个链接或按钮,可以关注或取消关注,不是吗?
-
不,先生,因为关注就像 +1 必须添加到数据库中,以便您可以检索您稍后关注的人的帖子...
-
您可以做一个简单的链接或按钮,对您的控制器进行 Ajax 调用,并关注或取消关注(添加或从数据库中删除)用户。您不需要表单,因为您不需要向用户询问任何数据。
标签: jquery ruby-on-rails