我正在构建一个基本的应用程序,其中各个lists
has_many
items
。我正在尝试在列表创建上实现AJAX并在lists#index
页面上显示。新列表创建正常,但在我手动刷新页面之前它们不会出现。这是错误,如服务器日志中所述:
List Exists (0.1ms) SELECT 1 AS one FROM "lists" WHERE ("lists"."id" IS NOT NULL) AND "lists"."slug" = ? LIMIT 1 [["slug", "new-list-again"]]
SQL (0.3ms) INSERT INTO "lists" ("name", "shared_with", "user_id", "slug") VALUES (?, ?, ?, ?) [["name", "New List Again"], ["shared_with", ""], ["user_id", 2], ["slug", "new-list-again-dc08b63c-1d57-42ea-a725-a2c5c185e529"]]
(0.7ms) commit transaction
Rendered lists/create.js.erb (7.9ms)
Completed 500 Internal Server Error in 22ms (ActiveRecord: 1.4ms)
NoMethodError - undefined method `valid?' for nil:NilClass:
app/views/lists/create.js.erb:1:in `_app_views_lists_create_js_erb___822718317456566494_70187652289300'
以下是我lists#index
页面上的相关代码:
<h1>My Lists (<%= @lists.count %>)</h1>
<% if @lists.count == 0 %>
<p>You don't have any lists yet! Why don't we remedy that?<p>
<% end %>
<div class='list-form'>
<%= render partial: 'lists/form', locals: { list: @list } %>
</div>
<div class="js-lists">
<%= render @lists %>
</div>
这是我的lists/_form
部分:
<div class="row">
<div class="col-xs-12">
<%= form_for @list, format: :js, remote: true do |f| %>
<div class="form-group col-sm-6">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control', placeholder: "Enter List Name" %>
</div>
<div class="form-group col-sm-6">
<%= f.label 'Share My List (Not Required)' %>
<%= f.text_field :shared_with, class: 'form-control', placeholder: "Enter Emails Separated by Commas" %>
</div>
<div class="text-center"><%= f.submit "Let's Go!", class: 'btn btn-primary' %></div>
<% end %>
</div>
</div>
这是我的lists/_list
部分:
<%= link_to list_path(list) do %>
<h4><%= list.name %>
<% if list.shared_with != "" %>
(Shared)
<% end %>
<% end %>
<small>( <%= list.items.count %> Items, <%= link_to "Edit", edit_list_path(list) %> | <%= link_to "Delete", list_path(list), method: :delete %> )</small></h4>
这是我的create.js.erb
文件:
<% if @item.valid? %>
$('.js-lists').prepend("<%= escape_javascript(render partial: 'lists/list', locals: { list: @list }) %>");
$('.list-form').html("<%= escape_javascript(render partial: 'lists/form', locals: { list: @new_list }) %>");
<% else %>
$('.flash').prepend("<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>×</button><%= flash.now[:alert] %></div>");
$('.new-list').html("<%= escape_javascript(render partial: 'lists/form', locals: { list: @list }) %>");
<% end %>
以下是create
中的lists_controller
方法:
def create
@list = List.new(list_params)
@list.user = current_user
@new_list = List.new
if @list.save
flash[:notice] = "Your list was saved successfully."
else
flash.now[:alert] = "Error creating list. Please try again."
end
respond_to do |format|
format.js
end
end
我对Ruby比较陌生,但对Javascript来说还是新手,所以如果有人能帮我指出我在哪里出错,我将不胜感激。新的list
肯定是在创建的,只有在您手动刷新页面后才会显示。
答案 0 :(得分:0)
您似乎在create.js.erb
中输入了错误的变量名称。您应该检查@list
的有效性,而不是@item