通过jquery使用集合更新rails部分

Updating rails partial with a collection through jquery

本文关键字:更新 rails 部分 集合 jquery 通过      更新时间:2023-09-26

我有一个允许用户发布更新的表单。一旦用户发布更新,我希望更新列表刷新。为了实现这一点,我使用Ajax和jQuery,并使用Rails。我遇到了麻烦,而试图让jquery渲染post feed部分虽然。

这是我使用的jquery

$(".microposts").html("<%= j render partial: 'shared/feed_item', collection: @feed_items %>")

目前,提要只是刷新并且不显示任何内容。我相信这是由于我试图传递@feed_items的方式。传递这个变量的最好方法是什么?

有人要控制器;

class MicropostsController < ApplicationController
before_action :signed_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def create
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save
        respond_to do |format|
            format.html { redirect_to root_url }
            format.js 
        end
    else
        @feed_items = []
        flash[:error] = "Failed to create micropost!"
        render 'static_pages/home'
    end
end
def destroy 
    @micropost.destroy
    flash[:success] = "Micropost deleted!"
        redirect_to root_url    
end
private
    def micropost_params
        params.require(:micropost).permit(:content)
    end
    def correct_user
        @micropost = current_user.microposts.find_by(id: params[:id])
        redirect_to root_url if @micropost.nil?
    end
end

@feed_items需要在控制器中的某处定义。@是Ruby中的一个特殊符号,表示当前类的实例变量。如果你在别处定义了它,它就变成了那个类的实例变量。

Rails有一些特殊的魔力,使控制器的实例变量在视图中可用。如果它不是控制器上的实例变量,它将无法工作。

def create
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save
        @feed_items = @micropost.do_whatever_to_build_the_feed_items
        respond_to do |format|
            format.html { redirect_to root_url }
            format.js 
        end
    else
        @feed_items = []
        flash[:error] = "Failed to create micropost!"
        render 'static_pages/home'
    end
end