好的,我正在向服务器发出 JQuery .post 请求以插入一些数据。它有时仅根据 Rails create 方法中的方法起作用。
以下是具体情况。我在前端有一个带有 Backbone.js 的 Rails 应用程序。在我的前端代码中,我提出了这个 .post 请求
$.post('/publications');
看起来很简单。我有一个出版物模型以及
resources :publications
在路由器中。现在在我的 Publications 控制器中,我将 create 方法扩充为以下内容:
def create
feed = Feedzirra::Feed.fetch_and_parse(publication_params[:url])
params = {:name => feed.title}
@publication = Publication.new(params)
respond_to do |format|
if @publication.save
format.html { redirect_to @publication, notice: 'Publication was successfully created.' }
format.json { render action: 'show', status: :created, location: @publication }
else
format.html { render action: 'new' }
format.json { render json: @publication.errors, status: :unprocessable_entity }
end
end
end
Feedzirra 是一个解析 RSS 提要的 gem。当我发出这样的 POST 请求时,我收到 500(内部服务器错误)和来自我的服务器日志的这条消息
NoMethodError (undefined method `title' for {}:Hash):
app/controllers/publications_controller.rb:28:in `create'
Rendered /Users/ericabt1/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (40.3ms)
Rendered /Users/ericabt1/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Users/ericabt1/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered /Users/ericabt1/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (54.7ms)
令我困惑的是,如果我选择与“标题”不同的方法,例如“条目”或“无”?POST 请求工作得很好。我知道“title”确实是一种方法,因为当我进入 Rails 控制台并创建一个测试 Feedzirra 对象并查看可用的各种方法时,我发现“title”就是其中之一。
为什么我的 POST 请求适用于其中一些方法而不适用于其他方法?!?!?!?!
* 更新* ***
在听取了 krabbi 和 Alexander Zolotko 的建议后,我开始玩 FeedZirra 回归的东西。它看起来像线
feed = Feedzirra::Feed.fetch_and_parse(publication_params[:url])
正在返回一个空哈希。
现在,当我在 rails 控制台中运行同一行并在其中硬编码一个 url 时,它会返回正确的哈希值,并且我能够获取标题和其他值。所以看起来问题出在
publication_params[:url]
仍在努力并接受建议:)
*更新第二部分*
我认为问题在于发布模型中没有 url 列。所以我进行了适当的迁移。所以这里是架构:
create_table "publications", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.string "url"
end
回到我在底部的控制器:
private
# Use callbacks to share common setup or constraints between actions.
def set_publication
@publication = Publication.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def publication_params
params.permit(:name, :url)
end
publication_params[:url] 仍然返回 nil。我也试过这条线:
params.require(:publication).permit(:url, :name)
这只是给了我 400 Bad request 错误