当我尝试在我的视图中使用ajax渲染微博时,我遇到了这个问题:
表单中的第一个参数不能包含nil或为空
正在创建Micoposts但由于某些原因它们在javascript文件中为零或空。我可以意识到我的索引视图中存在某种冲突,因为我正在呈现帖子形式和每个帖子的评论表单,所以我想也许是与我在索引视图中实例化的变量有关的因为当我替换时评论此行
<%= bootstrap_form_for([micropost, @comment], remote: true) do |f| %>
与
<%= bootstrap_form_for([micropost, micropost.comments.build], remote: true) do |f| %>
一切正常但我的评论表单中的字段错误没有显示
#posts_controller
def new
if logged_in?
@micropost = current_user.microposts.build
@comment = @micropost.comments.build
@feed_items = current_user.feed
else
end
def create
@micropost = current_user.microposts.build(micropost_params)
respond_to do |format|
if @micropost.save
format.html { redirect_to root_url }
format.js
else
format.html { render action: "index" }
format.js
end
end
end
# _form_micropost.html.erb
<%= bootstrap_form_for(@micropost, remote: true) do |f| %>
<% end %>
# _form_comment.html.erb
<%= bootstrap_form_for([micropost, @comment], remote: true) do |f| %>
<% end %>
create.js.erb
<% if @micropost.errors.any? %>
$("#form-micropost-container").html("<%=escape_javascript(render('shared/form_micropost')) %>");
<% else %>
var micropost = $("<%= escape_javascript(render(@micropost)) %>").hide().fadeIn("slow");
$("#feed-container").prepend(micropost);
<% end %>
答案 0 :(得分:0)
尝试明确传递所有参数:
#posts_controller
def new
if logged_in?
@micropost = current_user.microposts.build
@comment = @micropost.comments.build
@feed_items = current_user.feed
else
end
def create
@micropost = current_user.microposts.build(micropost_params)
@comment = #assign comment here
respond_to do |format|
if @micropost.save
format.html { redirect_to root_url }
format.js
else
format.html { render action: "index" }
format.js
end
end
end
# _form_micropost.html.erb
<%= bootstrap_form_for(micropost, remote: true) do |f| %>
<% end %>
# _form_comment.html.erb
<%= bootstrap_form_for([micropost, comment], remote: true) do |f| %>
<% end %>
create.js.erb
<% if @micropost.errors.any? %>
$("#form-micropost-container").html("<%=escape_javascript(render('shared/form_micropost', micropost: @micropost)) %>");
<% else %>
var micropost = $("<%= escape_javascript(render('form_comment', micropost: @micropost, comment: @comment)) %>").hide().fadeIn("slow");
$("#feed-container").prepend(micropost);
<% end %>