Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如果存在,则更新列,否则创建,但使用棘手的部分(我认为)_Ruby On Rails_Postgresql_Ruby On Rails 4_Postgresql 9.2 - Fatal编程技术网

Ruby on rails 如果存在,则更新列,否则创建,但使用棘手的部分(我认为)

Ruby on rails 如果存在,则更新列,否则创建,但使用棘手的部分(我认为),ruby-on-rails,postgresql,ruby-on-rails-4,postgresql-9.2,Ruby On Rails,Postgresql,Ruby On Rails 4,Postgresql 9.2,交易如下: 我正在创建一个rails RESTful API,用于在PostgreSQL数据库中存储信息,并使用父和子控制器以及父和子模型(示例名称) 我需要的是检查子记录是否已经存在,而不是按id。我需要检查子记录是否已经是具有相同“类型”和“父id”的记录 如果找到记录,我需要更新列“值”,但添加新的“值”,而不是替换,如: Child data 1: {type => type1, values => { info1 => info1, val1 => 1 }, p

交易如下: 我正在创建一个rails RESTful API,用于在PostgreSQL数据库中存储信息,并使用父和子控制器以及父和子模型(示例名称)

我需要的是检查子记录是否已经存在,而不是按id。我需要检查子记录是否已经是具有相同“类型”和“父id”的记录

如果找到记录,我需要更新列“值”,但添加新的“值”,而不是替换,如:

Child data 1: {type => type1, values => { info1 => info1, val1 => 1 }, parent_id => parent1}
Child data 2: {type => type1, values => { info2 => info2, val2 => 2 }, parent_id => parent1}

Final result: {type => type1, values => *[*{ info1 => info1, val1 => 1}, {info2 => info2, val2 => 2 }*]*, parent_id => parent1}    
我已经看到了一些主题,目前在子模型中有:

before_create :check_child_exists

private

def check_child_exists
    @child = Child.find_by_type_and_parent_id(self.type, self.parent_id)
    if @child != nil
        @child.update_attribute(:value, <*>) # <*> = hash + newhash (an array of hashes)
    end
end
创建前:检查子项是否存在
私有的
def check_child_存在
@child=child.find\u by\u type\u和\u parent\u id(self.type,self.parent\u id)
如果@child!=无
@update_属性(:value,)#=hash+newhash(一个哈希数组)
终止
终止
有人能帮我吗?我将不胜感激。 如果需要任何其他信息,请告诉我

提前感谢,

def update_previous_child
  conditions = {type: self.type, parent_id: self.parent_id}

  if existing_child = Child.find_by(conditions) # or Child.where(conditions).last
    new_value = (existing_child.value || []) + [new_hash]
    existing_child.update_attribute(:value, new_value)
  end
end
那应该是你想要的。但每次创建子对象时,只会更新最后一个。如果要更新所有现有行,请执行以下操作:

def update_previous_children
  conditions = {type: self.type, parent_id: self.parent_id}

  Child.where(conditions).each do |existing_child|
    new_value = (existing_child.value || []) + [new_hash]
    existing_child.update_attribute(:value, new_value)
  end
end

如果你知道如何正确地序列化你的新散列,你可以在
ActiveRecord::Relation
返回的
where
上编写一些SQL来使用
update\u all
,而不是把它变成一个数组并在每个条目上使用
update\u属性。

非常感谢你的回答,我会在可能的时候尝试一下(我仍在api的测试部分工作)。一个小问题:我不明白您在创建子对象时说“只更新最后一个”的部分,您能澄清一下吗?可能有多个子对象满足您的条件标准。如果使用第一个方法,则只更新最后一个(本例中ID最高的一个)将被更新。哦,对了,情况并非如此,因为相同类型和父\u ID的所有子记录都应位于一个数据库记录中。多行的情况不是问题,因为父\u ID和类型可以视为主键。感谢您的帮助。(我会支持你的评论,但我不能因为我没有足够的声誉,对不起:()