bulk update objects using form in rails

I have a person model and a quotes model. Each person can have many quotes associated with them, which in turn has things like Author, Text, Url associated with them. In practice really only one person has a quotes object but all people could potentially have one.

I'm trying to have a dirt simple bulk moderate tool on quotes. As in, users can type in quotes and an admin can go and have all of the quotes of a particular person (but like in practice, only one will have them) and check a box which sets a boolean approved to 0 or 1. When the quotes are actually displayed, they're filtered by this field.

I'm getting really mixed up trying to create a form that updates these all in bulk. I got the form to display all of them as so:

<% form_for :quotes, :html => { :method => :put }, :url => {:controller => "quote", :action => "bulk_update", } do |quote_form| %> <% @person.quotes.each do |quote| %> <p> <% fields_for "quotes[id][]", quote do |fields| %> Text.... <%= fields.check_box :approved %><br><br> <% end %> </p> <% end %> <%= submit_tag 'Update' %> <% end %>

I just have an incredibly generic thing in my bulk update controller which is basically like a normal update controller. I'm not sure what to put in there. I could try to put all the quotes which I probably should but I don't know how to get to that variable anyway because I'm doing all of this from whithin the Person view etc. The controller is osmething like this:

def bulk_update @quote = Quote.find(params[:id]) end

I guess I'm getting confused about the ID that should be in there and what should be getting passed in. Should the person ID be part of this at all? Like I said, I don't really care if technically all quotes are displayed on that page, they don't need to be sorted by user.

I'm getting parameters that look like this:

"quotes"=>{"id"=>{"6"=>{"approved"=>"0"}, ..

but it complains about not finding a quote without an ID. I don't care about the ID since I want to bulk update all of them. It seems like this particular stucture would map several ids, but maybe (probably) i have to change my controller to compensate for that, not sure how though. It also doesn't work when I try to remove the quotes par tof the hash and just have"id"=>{"6"=>{"approved"=>"0"}, .. as my parameters.

EDIT: I found a statement called update_all, but I don't know how to selectively pass it what I need...


I found the following approach to be flexible specially for error handling as well:

def bulk_update
quotes = params["quotes"]["id"]
quotes.each do |quote_id,quote_attrs|
quote = Quote.find(quote_id)
# Other logic of interest like error handling
# . . .
# Don't forget to render or redirect to the proper view


The proper way to do this is by moving the update logic to the model:

class QuotesController < ApplicationController
def bulk_update
errors = Quote.bulk_update(params["quotes"]["id"])
# Other logic of interest like error handling
# . . .
# Don't forget to render or redirect to the proper view

class Quote < ActiveRecord::Base
def bulk_update
errors = {}
quotes.each do |quote_id,quote_attrs|
quote = Quote.find(quote_id)
unless quote.update_attributes(quote_attrs)
errors[quote_id] = qoute.errors

I would make something like that:

def self.bulk_update(attributes)
where(id: attributes.keys).each_with_object({}) do |quote, errors|
unless quote.update_attributes(attributes["#{quote.id}"])}
errors["#{quote.id}"] = entry.errors

In this method you'll only load the quotes that are concerned.

Gregory Horion -

After looking at this code:

def bulk_update
quotes = params["quotes"]["id"]
quotes.each do |quote_id,quote_attrs|
quote = Quote.find(quote_id)

I thought it might be more concise to do just this:

Quote.where(:condition => "value").collect{|x| x.update_attributes(quote_attrs)}

Category:ruby on rails Time:2009-10-01 Views:1

Related post

  • How to check updated object in rspec in rails 3.1.0? 2012-02-09

    We use rspec and factorygirl to test update in invoice controller. The rspec code is: inv = Factory(:invoice, :paid_out => false) get 'update', :id => inv.id, :invoice => {:paid_out => true} How to exam values in updated object inv? We tr

  • How to calculate and use latest updated object in Ruby on Rails? 2012-03-20

    I have Projelements, which are like: Milestone Task ... etc ... Each Projelement can have one or more embedded Comments (thanks to Mongoid). I want to be able to easily say: Give me a list of Projelements sorted by when they were last updated Where l

  • Update object array values in rails view 2010-07-13

    I have @table_name(object array) contain many objects. I want to replace its column values one by one with my values.. i have use <% for group_permission in @table_name %> <%end%> How i change Please help me --------------Solutions-------

  • Casting object to CheckBox in bulk updates 2011-06-14

    I was following this so far everything is fine with a textbox but when try to modify it to checkbox it gives an error: Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.Web.UI.WebControls.CheckBox'. Its working when I

  • Bulk update has_many relationship model from belongs_to model 2011-06-20

    class Project < ActiveRecord::Base has_many :pages attr_accessible :name, :class_name, :content, :style def bulk_update_pages(attributes) for a in attributes do pages.find(a['id'].to_i).update_attributes(a) if pages.exists?(a['id']) end end end cl

  • JPA: How do I synchronize the persistence context with the result of the bulk update or delete? 2009-09-23

    There's a statement in the ejb-3_0-fr-spec-persistence.pdf which reads The persistence context is not synchronized with the result of the bulk update or delete So if I do a query.executeUpdate which deletes rows from a table. Those same rows still ex

  • Is there a bulk update operation for all entities in Core Data? 2009-11-09

    On the iPhone, Does Core Data have a way to bulk update a field for every instance of an entity that it's storing? Something like update some_entities set some_count = 0 where some_count > 0 Or do I just have to instantiate every entity, set the v

  • Linq to Nhibernate Bulk Update Query Equivelent? 2010-01-22

    Not sure if I'm missing anything here. Basically, I am looking for Linq to Nhibernate to do the following SQL statement: update SomeTable set SomeInteger = (SomeInteger + 1) where SomeInteger > @NotSoMagicNumber Is there any way to do that? Thanks

  • Perform conditional bulk update in Linq to SQL 2010-01-25

    I have a SQL table that stores photos with a smallint SortOrder field. Users can insert new photos, specifying a decimal sort order to place the new record between 2 existing photos (or before the first photo). The SortOrder will be stored as a small

  • Bulk updating a table 2010-10-01

    I want to update a customer table with a spreadsheet from our accounting system. Unfortunately I can't just clear out the data and reload all of it, because there are a few records in the table that are not in the imported data (don't ask). For 2000

  • Bulk update/upsert in MongoDB? 2010-12-14

    Is it possible to do bulk update/upsert (not insert) in MongoDB? If yes, please point me to any docs related to this? Thanks --------------Solutions------------- You can use the command line program mongoimport it should be in your MongoDB bin dir ..

  • What are some techniques for testing optimizations to ActiveRecord bulk model object creation? 2011-10-03

    I am in the process of optimizing a contact importer tool that process a large list of email address and creates contact objects. The brunt of the changes will involve creating the contacts all at once rather than individually using standard ActiveRe

  • Clearing session, flushing, refreshing, after hibernate bulk updates? 2011-10-13

    As we know, when doing a bulk update to the DB with hibernate (even in HQL), the changes made are not replicated to the entities stored in the current session. So i may call session.refresh to load the modifications to my session entities. We often c

  • heterogeneous bulk update in mongodb 2011-10-19

    I know that we can bulk update documents in mongodb with db.collection.update( criteria, objNew, upsert, multi ) in one db call, but it's homogeneous, i.e. all those documents impacted are following one kind of criteria. But what I'd like to do is so

  • How to modify a model after bulk update in django? 2013-05-21

    I try some code like this: mymodels = MyModel.objects.filter(status=1) mymodels.update(status=4) print(mymodels) And the result is an empty list I know that I can use a for loop to replace the update. But it will makes a lot of update query. Is there

  • In a Dynamic Data custom page how do I retrieve the just updated object? 2008-10-28

    I am using ASP.NET Dynamic Data and have a custom page. In this page I have a handle on the DetailsView inserted event where I would like to do something based on the value of the recently updated object. However, I can't put the event handling in th

  • Binding to an auto-updating object? 2009-03-05

    Is there an object or interface I can use to make an auto-updating object, and have those updates filter through to the UI in WPF? Basically I'm looking for something like this: <TextBlock Text="{Binding Source={StaticResource myClass}, Path=DataO

  • TreeViewer#update(Object element, String[] properties); what do properties refer to? 2009-07-23

    I have been wondering about the parameter 'properties' in the method TreeViewer#update(Object element, String[] properties). What are they? What do they refer to? I am not sure what goes into the String[] - are there predefined constants to use? Or a

  • bulk update/delete entities of different kind in db.run_in_transaction 2010-05-04

    Here goes pseudo code of bulk update/delete entities of different kind in single transaction. Note that Album and Song entities have AlbumGroup as root entity. (i.e. has same parent entity) class Album: pass class Song: album = db.ReferenceProperty(r

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 1.126 (s). 13 q(s)