将我要创建的对象的ID保存在另一个对象的外键中

时间:2019-06-11 23:35:06

标签: ruby-on-rails ruby-on-rails-4

我有两个模型:ActivityLocationActivity

Activity可以有一个位置,这个位置可以是roomlocation,并且此信息我保存在表location_activities中,该表具有外键{{ 1}}。

在创建activity_id并选择位置类型时,我需要将activity的ID保存在表activity的{​​{1}}中

activity_id

我有此代码,但location_activities记录未保存在我的数据库中

我该如何解决?

2 个答案:

答案 0 :(得分:0)

它不会被保存,因为您仅对其进行了初始化,但从未保存。另外,您尝试在保存之前将@activtity.id作为外键传递,此时@activity没有id。应该是:

def create
  @activity = Activity.new(activity_params)

  if @activity.save
    add_location(@activity)
    render json: {status: 'created', message: 'Activity save'}
  else
    render json: @activity.errors, status: :unprocessable_entity
  end
end

private

def add_location(activity)
  return if params[:activity][:type_place_activity] != RoomEvent.name

  room_event = RoomEvent.find(params[:activity][:room_event][:id])
  activity.location_activities.create(activity_place: room_event)
end

答案 1 :(得分:0)

尽管Vasilisa的答案可以解决问题,但我认为逻辑不属于控制器。我会这样更改ActivitiesController:

$phone1 = new Google_Service_PeopleService_PhoneNumber();
$phone2 = new Google_Service_PeopleService_PhoneNumber();
$phone1->setValue('0777677305');
$phone2->setValue('0774112128');

$person->setPhoneNumbers([$phone1,$phone2]);

$exe = $people_service->people->createContact($person)->execute;

然后将save_with_location_activities方法添加到“活动”模型中,如下所示:

def create
  @activity = Activity.new(activity_params)
  if @activity.save_with_location_activities(params[:activity][:room_event][:id])
    render json: { status: 'created', message: 'Activity save' }
  else
    render json: @activity.errors, status: :unprocessable_entity
  end
end