我尝试使用AJAX添加新对象,但我得到的只是#34;无法加载资源:服务器响应状态为500(内部服务器错误)"。
我花了大约4个小时试图找到解决方案,接着是2个教程,但这个错误从未离开过我。
我的characters_controller.rb
class CharactersController < ApplicationController
def index
@characters = Character.all.order("id DESC")
end
def create
@character = Character.new(params[:character])
if @character.save
flash[:notice] = "Successfully created post."
end
respond_to do |format|
format.js
end
end
end
index.html.erb
<div class="header">
<p>All Hobbit characters</p>
</div>
<div class="characters">
<%= render @characters %>
</div>
<%= form_for(Character.new, :remote => true) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
create.js.erb
<% if @character.new_record? %>
$('input#character_name').effect('highlight', {color: 'red'});
<% else %>
$('div#characters').append("<%= escape_javascript(render @character) %>");
$('div#<%= dom_id(@character) %>').effect('highlight');
<% end %>
模型仅包含:名称存在验证
答案 0 :(得分:2)
从Rails 4开始,您无法将params[:character]
直接传递给Character.new
方法。尝试这样的事情:
def create
@character = Character.new(character_params)
if @character.save
flash[:notice] = "Successfully created post."
end
respond_to do |format|
format.js
end
end
private
def character_params
params.require(:character).permit(:name)
end