ajax将信息添加到数据库

时间:2012-09-18 11:01:46

标签: ruby-on-rails jquery activerecord

虽然我已经读过你可以轻松执行ajax请求,但我仍然相当新的东西上的ruby。我想要做的是在数据库表中添加一个新行,并从中传递一些变量。

目前我所拥有的是

%li= link_to image_tag('trans.gif', :border => 0, :size => '16x16', :class => 'i-16-tick'), availabilities_path(:team_id => schedule.team_id, :user_id => current_user, :schedule_id => schedule.id), :remote => true, :method => :post, :title => 'Accept', :rel => 'tooltip-html'

控制器代码

`#POST / availability   #POST /availabilities.json   def创建     @availability = Availability.new(params [:availability])

respond_to do |format|
  if @availability.save
    format.html { redirect_to @availability, :notice => 'Availability was successfully created.' }
    format.json { render :json => @availability, :status => :created, :location => @availability }
  else
    format.html { render :action => "new" }
    format.json { render :json => @availability.errors, :status => :unprocessable_entity }
  end
end

端 `

虽然它如何知道要传递给数据库的变量?

这就是目前正在发生的事情

Processing by AvailabilitiesController#create as HTML Parameters: {"schedule_id"=>"18", "team_id"=>"1", "user_id"=>"38"} User Load (1.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 38 LIMIT 1 (0.4ms) BEGIN SQL (20.1ms) INSERT INTO "availabilities" ("available", "created_at", "schedule_id", "team_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["available", nil], ["created_at", Tue, 18 Sep 2012 23:07:26 EST +10:00], ["schedule_id", nil], ["team_id", nil], ["updated_at", Tue, 18 Sep 2012 23:07:26 EST +10:00], ["user_id", nil]] (10.5ms) COMMIT

2 个答案:

答案 0 :(得分:1)

如果要将多个变量传递给服务器,请将它们包含在http请求中。这对于AJAX请求和常规请求都是如此。例如:

<%= link_to 'Send data', accept_availabilty( player, :my_variable => value1, :my_variable => value2), :remote => true %>

通常,虽然提交的内容比较复杂,但您只想使用远程表单,而不仅仅是简单的链接。

答案 1 :(得分:0)

如果您想将信息传递给rails应用,则需要放置

:remote => true

到form_for标签,然后您的控制器就能将这些参数传递给您的模型。