Rails find_or_create_by有/无在哪里

时间:2015-06-20 10:33:07

标签: ruby-on-rails ruby activerecord

假设我有一个名为@Override public View getView(int position, View convertView, ViewGroup parent) { final View view; Recipe recipe = this.getItem(position); if (convertView != null){ view = convertView; view.setTag(recipe.getId()); } else{ view = myActivity.getLayoutInflater().inflate(R.layout.recipe_item, parent, false); view.setTag(recipe.getId()); } ImageView imageView = (ImageView) view.findViewById(R.id.filtered_recipes_list_image_view); // final String foo = "https://cms-assets.tutsplus.com/uploads/users/21/posts/19431/featured_image/CodeFeature.jpg"; final String foo = "http://www.miasmat.no/wp-content/uploads/2015/05/OvnsbaktKveite9.jpg"; Picasso.with(myActivity).setIndicatorsEnabled(true); Picasso.with(myActivity).setLoggingEnabled(true); Picasso.with(myActivity).load(foo).into(imageView, new Callback() { @Override public void onSuccess() { Log.i("TAGZ", "Success! url = " + foo); } @Override public void onError() { Log.i("TAGZ", "Error! url = " + foo); } }); return view; } 的模型。我希望Task完成一些任务。

find_or_create_by

此模型有效,但创建t = Task.where(done: false).find_or_create_by(title: 'epic') 等于epic且title等于false的任务。我希望done的查询搜索等于false,但我不希望新记录done等于false。我该怎么办?

1 个答案:

答案 0 :(得分:4)

您可以使用名为find_or_initialize_by的内容。它只会初始化记录,但不会创建记录。这样,您可以稍后覆盖以下属性:

 task = Task.where(done: false).find_or_initialize_by(title: 'epic').first
 task.done = true # or nil or whatever you want!
 task.save

我只使用task.done = true保存了第一条记录。如果有多个记录,您可以使用each遍历所有记录,并将它们全部保存。

修改

Task.where(:done => false).first_or_initialize do |task|
  task.done = true
  task.title = 'epic'
end