Ruby on rails .save将在Rails的id字段中设置NULL
以下是模型文件:Ruby on rails .save将在Rails的id字段中设置NULL,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,以下是模型文件: class ProfileTag < ActiveRecord::Base def self.create_or_update(options = {}) id = options.delete(:id) record = find_by_id(id) || new record.id = id record.attributes = options puts "record.profile_id is" pu
class ProfileTag < ActiveRecord::Base
def self.create_or_update(options = {})
id = options.delete(:id)
record = find_by_id(id) || new
record.id = id
record.attributes = options
puts "record.profile_id is"
puts record.profile_id
record.save!
record
end
end
我不确定我是否理解为什么INSERT
会正确地将值放入profile\u id
,但在更新时它会将其设置为NULL
[编辑]
在ProfileController中:
def update
#...stuff. Set tags array.
save_tags(tags) #These tags are correct. Verified by printouts before and after this call.
respond_to do |format|
if @profile.update_attributes(params[:profile])
flash[:notice] = 'Profile was successfully updated.'
#format.html { redirect_to(@profile) }
format.html { redirect_to :action=>'show' }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }
end
end
end
def save_tags(tags)
profile = find_profile #finds the correct profile. And I confirm that it exists with a printout
tags.each do |t|
ProfileTags.create_or_update(:profile_id => profile.profile_id, :tag_id => t.id)
end
end
如果你需要更多的细节,请告诉我。我认为save
功能除了将插入到数据库中之外,还有很多其他功能,但我不知道需要指定什么才能正确设置profile\u id
save!它本身不应该这样做
也许你的问题是方法的名称。ActiveRecord::Base已经有一个名为create_或_update(请参阅)的方法,该方法由save!调用也许更换它会导致这个奇怪的问题
尝试将方法的名称更改为其他名称,这可能会有所帮助。您首先没有将id属性传递给create\u或\u update方法,因此不需要调用它,只需调用create即可,如下所示:
def save_tags(tags)
profile = find_profile #finds the correct profile. And I confirm that it exists with a printout
tags.each do |t|
ProfileTag.create(:profile_id => profile.profile_id, :tag_id => t.id)
end
end
看这句台词:
ProfileTags.create_or_update(:profile_id => profile.profile_id, :tag_id => t.id)
我相信您希望传递的是profile.id
,而不是profile.profile\u id
(可能为空)。您没有进行更新的回调吗?我是RoR新手。在看到你的评论之前,我不知道回拨是什么。你是说我写了回电?在你存钱之前我没有。此外,ProfileTagsController中没有更新操作。抱歉,我不明白你的问题。查看日志,你的代码在保存过程中没有将profile\u id
设置为空,而是将id
设置为空,这将是行id=options.delete(:id)
的结果。你有没有偷看一下你的数据库,看看到底发生了什么?是否可以展开日志条目以包含自定义行?是否在配置文件模型中为
使用accepts\u nested\u attributes\u?可以查看日志文件并向我们显示传递给更新操作的参数吗?感谢您的建议,Slobodan,但它不起作用。我仍然得到将profile\u id设置为NULL的更新。你能从你调用create\u或\u UPDATE的控制器发布代码吗?我假设你的profile模型中有类似has\u many:profile\u标记的东西。如果是这样,那么您的问题可能是@profile.update_attributes(params[:profile]),它从没有任何标记的内存中保存概要文件(因此将其设置为null)。尝试注释掉控制器中的save_标记调用,并在日志中查看是否仍然存在更新查询-如果仍然存在,则更新_属性是“罪魁祸首”。
ProfileTags.create_or_update(:profile_id => profile.profile_id, :tag_id => t.id)