全部,我在我的控制器中有一个我直接打电话的功能。但是,一旦执行,我希望它改为跟随或不跟随。我使用Act作为追随者宝石并且在改变我的跟随或不适当地跟随时遇到一些问题。有人可以指出我正确的方向吗?
在我的控制器中:
Createcampaigncontroller.rb
def follow
@campaign = Createcampaign.find(params[:id])
if user_signed_in? && !current_user.following?(@campaign)
current_user.follow(@campaign)
#RecommenderMailer.new_follower(@user).deliver if @user.notify_new_follower
flash[:notice] = "You are now following #{@current_user.username} #{@campaign.name}."
respond_to do |format|
format.html { redirect_to(:back) }
format.js {render :action => "follow_button" }
#redirect_to :back
end
else
flash[:error] = "You must <a href='/users/sign_in'>login</a> to follow # {@campaign.name}.".html_safe
redirect_to root_url
end
end
def unfollow
if current_user
@campaign = Createcampaign.find(params[:id])
current_user.stop_following(@campaign)
flash[:notice] = "You are no longer following #{@campaign.name}."
#format.js {render :action => "follow" }
redirect_to :back
else
flash[:error] = "You must <a href='/users/sign_in'>login</a> to unfollow #{@campaign.name}.".html_safe
end
end
在我看来,我正在玩基于标准显示按钮的选项。
<% if current_user.id == @campaignid%>
you own this
<%end%>
<%else%>
<% if current_user.following?(@campaign) %>
<%= link_to "Unfollow", unfollow_createcampaign_path(@campaign),class: "btn btn-success btn-outline btn-sm" %>
<%elsif%>
<%= link_to "follow", follow_createcampaign_path(@campaign),class: "btn btn-success btn-outline btn-sm" %>
<%end%>
这似乎没有帮助。我查看了一些Rails示例,但它们涉及提交字段或表单。也许我需要改变我的方法。任何帮助表示赞赏。
答案 0 :(得分:0)
使用ajax提交您的链接。为此添加&#34; remote:true&#34;您的链接选项也会添加一个链接以便稍后引用它:
<%= link_to "follow", follow_createcampaign_path(@campaign), id: "follow<%= @campaign.id %>", remote:true, class: "btn btn-success btn-outline btn-sm" %>
这将通过ajax将您的链接点击提交给您的控制器。在您的控制器中使用javascript文件进行响应:
def follow
respond_to do |format|
format.html { redirect_to(:back) }
format.js
end
当你这样做时,rails希望你有一个带有控制器动作名称的javascript文件,在这种情况下(follow.js)在你的Createcampaign视图文件夹中。
在您的follow.js.erb文件中,您可以放置响应对象或编写您的javascript以替换您链接的类和href。 例如,这是我发送到我的帖子的javascript响应:
$("#like_<%= @post.id %>").removeClass('glyphicon-heart-empty').addClass('glyphicon-heart');
$("#like_<%= @post.id %>").attr('href', "<%= unlike_post_path(@micropost.id) %>");
第一行删除前一个类(空心)并用新类(填充的心)替换它。第二行,将from_ref链接从like_post_path更改为incons_post_path。一旦你将其分解,这很简单。