带有Backbone的Rails不会保存has_many数据

时间:2013-11-21 12:02:07

标签: ruby-on-rails json backbone.js ruby-on-rails-4

我真的没有轨道​​经验。我可能正在做一些不合适的事情。如果是这样,请告诉我。
我正在尝试将has_many数据保存到group belongs_to building。并building has_many groups。我将数据作为JSON从骨干发送到rails。

{
max: "10"
max_age: "70"
min_age: "50"
name: "new group"
building: "kvbmPQQo"
}

在我的groups_controller.rb中,我尝试首先找到building id_token,然后用所述建筑物保存该组。

def create
  @building = Building.where(:id_token => params[:building]).first
  @group = Group.new(group_params)
  @group.building = @building
  @group.save
  respond_to do |format|
    format.json { render :json => @group }
  end
end

当我运行这个时,我不确切知道问题是什么。 它不会保存。以下是终端中记录的内容。

Started POST "/groups" for 127.0.0.1 at 2013-11-21 06:48:04 -0500
Processing by GroupsController#create as JSON
  Parameters: {"name"=>"G", "max"=>"2", "min_age"=>"2", "max_age"=>"2", "building"=>"kvbmPQQo", "group"=>{"name"=>"G", "min_age"=>"2", "max_age"=>"2"}}
  Building Load (0.3ms)  SELECT "buildings".* FROM "buildings" WHERE "buildings"."id_token" = 'kvbmPQQo' ORDER BY "buildings"."id" ASC LIMIT 1
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
Completed 200 OK in 23ms (Views: 0.2ms | ActiveRecord: 1.1ms)

另外,如果你看到我正在做的事情完全没有“铁路”,请告诉我。
我的groups.rbbelongs_to :building而我的building.rbhas_many :groups

1 个答案:

答案 0 :(得分:2)

def create

  # Find the building by its token
  @building = Building.find_by(:id_token => params[:building])
  # or
  # @building = Building.where(:id_token => params[:building]).first

  # Create a new building group with parameters
  @group = @building.groups.create(params[:group])

  respond_to do |format|
    format.json { render :json => @group }
  end

end