我有一个用户列表,我想删除点击"删除"链接在同一行。
查看:
loaders: [{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components|externals)/,
cacheable: true,
loader: 'babel-loader',
query: {
presets: 'es2015',
//optional: ['runtime', 'es7.asyncFunctions'],
//retainLines: true,
cacheDirectory: true
}
}, {
test: /\.js$/,
loader: 'transform/cacheable?brfs!transform/cacheable?envify',
exclude: /(node_modules|bower_components|externals)/,
cacheable: true
}, {
//test: /\.css$/,
//loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
test: /\.css$/,
loader: 'style-loader!css-loader',
cacheable: true
//exclude: /(node_modules|bower_components)/
}, {
test: /\.scss$/,
loader: 'style!css!sass?sourceMap',
cacheable: true,
exclude: /(node_modules|bower_components|externals)/
}, {
test: /\.sass$/,
// Passing indentedSyntax query param to node-sass
loader: 'style!css!sass?indentedSyntax&sourceMap',
cacheable: true,
exclude: /(node_modules|bower_components|externals)/
}, {
test: /\.less$/,
loader: 'style!css!less?strictMath&noIeCompat',
cacheable: true,
exclude: /(node_modules|bower_components|externals)/
}, {
test: /\.html$/,
cacheable: true,
loader: 'html',
query: {
attrs: false // indicates that image src should not be processed
}
}, {
test: /\.json$/,
cacheable: true,
loader: 'json'
}, {
test: /\.woff/,
loader: 'url?prefix=font/&limit=10000&mimetype=application/font-woff'
}, {
test: /\.ttf/,
loader: 'file?prefix=font/'
}, {
test: /\.eot/,
loader: 'file?prefix=font/'
}, {
test: /\.svg/,
loader: 'file?prefix=font/'
}]
用户控制器:
# users/index.html.erb
<ul class="users">
<%= render @users %>
</ul>
# users/_user.html.erb
<li id="user-<%= user.id %>">
<%= link_to user.email, user %>
<% if current_user.admin? %>
<%= link_to "delete", user, remote: true, method: :delete, data: { confirm: "You sure?" } %>
<% end %>
</li>
要删除列表元素的javascript是:
# users_controller.rb
def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted"
respond_to do |format|
format.html { redirect_to users_url }
format.js
end
end
单击时没有任何反应,但在页面刷新时,资源被正确销毁。检查服务器的LOG我看到以下错误:
在40ms内完成500内部服务器错误(ActiveRecord:5.0ms)
ActionView :: Template :: Error(未定义的局部变量或方法
# users/destroy.js.erb $("li#<%= user.id %>").remove();
_ app_views_users_destroy_js_erb ___ 2066095411338793994_74738360&#39;
app / controllers / users_controller.rb:46:在`destroy&#39;
你能帮助我理解错误的位置以及为什么用户&#39;未定义?感谢
我知道这个问题有很多q&amp; a 类似的,我实际上构建了我的代码来咨询这些问题。不过,我被困住了,我需要支持。请不要将问题标记为重复。
答案 0 :(得分:1)
你的destroy.js.erb模板没有获取用户变量,因为它未定义。尝试:
list[3] = input.Skip(3).Take(3).ToArray();
和
def destroy
@user = User.find(params[:id])
@user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.js
end
end
这是有效的原因是因为rails通过使用@前缀设置变量将数据从控制器传递到视图。所以你将@user设置为你从数据库中获取的模型的实例,然后你在该模型上调用.destroy,它被删除了,然后你渲染了你的destroy.js模板,其中也有@user,并且您删除了与&#39; li#233&#39;匹配的列表项选择器或任何id整数
答案 1 :(得分:0)
您没有定义user
变量。
您可以将@user_id
保存在变量中,以便在js.erb
中访问。像那样:
def destroy
@user_id = params[:id]
...
end
然后:
$("li#<%= @user_id %>").remove();