我真的没有轨道经验。我可能正在做一些不合适的事情。如果是这样,请告诉我。
我正在尝试将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.rb
有belongs_to :building
而我的building.rb
有has_many :groups
答案 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