我的网站上需要一个按钮,可以将信息发送到控制器的create动作(“ pagetimes”)。尽管它没有发送我指定的所有数据,但似乎仍在工作- 可能与我无法构造数据向量有关。我已经通过以下方式在config / routes.rb文件中提供了POST请求:post 'pagetimes/create'
post 'pagetimes/create'
在application.js中:
function submitForm() { alert("checked the button - worked"); $.ajax({ type:'POST', url: '/pagetimes/create', data: { pagename: "whatever", start: 7, end: 21 } , }); }
其中:pagename,:start和:end是我的数据表中的列(字符串,整数,整数),并且可以在模型中访问,并且可以在手动输入“新”页面中显示的页面时间获得。
:pagename
:start
:end
在我的页面视图中:
<button type="button" onclick="submitForm()">Send data</button>
其他一切都是很标准的。我可以在数据库中看到该帖子已成功提交,但是我尝试填充的3个数据字段均为NULL。可能这与我如何构建该data: {}领域有关?
data: {}
O / w,Win7上的Rails 3,没有使用其他可能与此有关的花哨内容…
更新1:这就是我尝试发布的表单源代码。也许是我不正确地引用字段的情况?
<div class="form-inputs"> <div class="control-group string optional pagetime_pagename"><label class="string optional control-label" for="pagetime_pagename">Pagename</label><div class="controls"><input class="string optional" id="pagetime_pagename" name="pagetime[pagename]" size="50" type="text" /></div></div> <div class="control-group integer optional pagetime_start"><label class="integer optional control-label" for="pagetime_start">Start</label><div class="controls"><input class="numeric integer optional" id="pagetime_start" name="pagetime[start]" step="1" type="number" /></div></div> <div class="control-group integer optional pagetime_end"><label class="integer optional control-label" for="pagetime_end">End</label><div class="controls"><input class="numeric integer optional" id="pagetime_end" name="pagetime[end]" step="1" type="number" /></div></div> </div>
更新2:这是我的日志,其中包含POST:
Started POST "/pagetimes/create" for 127.0.0.1 at 2014-01-02 12:45:48 -0500 Processing by PagetimesController#create as */* Parameters: {"end"=>"21", "pagename"=>"whatever", "start"=>"7"} [1m[35mUser Load (1.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1 [1m[36m (0.0ms)[0m [1mbegin transaction[0m [1m[35mSQL (15.0ms)[0m INSERT INTO "pagetimes" ("created_at", "end", "pagename", "start", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?) [["created_at", Thu, 02 Jan 2014 17:45:48 UTC +00:00], ["end", nil], ["pagename", nil], ["start", nil], ["updated_at", Thu, 02 Jan 2014 17:45:48 UTC +00:00], ["user_id", 1]] [1m[36m (7.0ms)[0m [1mcommit transaction[0m Redirected to http://localhost:3000/pagetimes/22 Completed 302 Found in 91ms (ActiveRecord: 24.0ms)
更新3:控制器动作
def create @pagetime = Pagetime.new(params[:pagetime]) @pagetime.user = current_user respond_to do |format| if @pagetime.save format.html { redirect_to @pagetime, notice: 'Pagetime was successfully created.' } format.json { render json: @pagetime, status: :created, location: @pagetime } else format.html { render action: "new" } format.json { render json: @pagetime.errors, status: :unprocessable_entity } end end end
function submitForm() { alert("checked the button - worked"); $.ajax({ type:'POST', url: '/pagetimes/create', data: $.param({ pagetime: {pagename: "whatever", start: 7, end: 21 }}) }); }