Search Results

Search found 67 results on 3 pages for 'randombits'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • Ruby on Rails: reducing complexity of parameters in a RESTFul HTTP POST request (multi-model)

    - by randombits
    I'm using cURL to test a RESTFul HTTP web service. The problem is I'm normally submitting a bunch of values normally like this: curl -d "firstname=bob&lastname=smith&age=25&from=kansas&someothermodelattr=val" -H "Content-Type: application/x-www-form-urlencoded" http://mysite/people.xml -i The problem with this is my controller will then have code like this: unless params[:firstname].nil? end unless params[:lastname].nil? end // FINALLY @person = People.new(params[:firstname], params[:lastname], params[:age], params[:from]) etc.. What's the best way to simplify this? My Person model has all the validations it needs. Is there a way (assuming the request has multi-model parameters) that I can just do: @person = People.new(params[:person]) and then the initializer can take care of the rest?

    Read the article

  • Ruby on Rails 2.3.5: Populating my prod and devel database with data (migration or fixture?)

    - by randombits
    I need to populate my production database app with data in particular tables. This is before anyone ever even touches the application. This data would also be required in development mode as it's required for testing against. Fixtures are normally the way to go for testing data, but what's the "best practice" for Ruby on Rails to ship this data to the live database also upon db creation? ultimately this is a two part question I suppose. 1) What's the best way to load test data into my database for development, this will be roughly 1,000 items. Is it through a migration or through fixtures? The reason this is a different answer than the question below is that in development, there's certain fields in the tables that I'd like to make random. In production, these fields would all start with the same value of 0. 2) What's the best way to bootstrap a production db with live data I need in it, is this also through a migration or fixture? I think the answer is to seed as described here: http://lptf.blogspot.com/2009/09/seed-data-in-rails-234.html but I need a way to seed for development and seed for production. Also, why bother using Fixtures if seeding is available? When does one seed and when does one use fixtures?

    Read the article

  • Multiple key/value pairs in HTTP POST where key is the same name

    - by randombits
    I'm working on an API that accepts data from remote clients, some of which where the key in an HTTP POST almost functions as an array. In english what this means is say I have a resource on my server called "class". A class in this sense, is the type a student sits in and a teacher educates in. When the user submits an HTTP POST to create a new class for their application, a lot of the key value pairs look like: student_name: Bob Smith student_name: Jane Smith student_name: Chris Smith What's the best way to handle this on both the client side (let's say the client is cURL or ActiveResource, whatever..) and what's a decent way of handling this on the server-side if my server is a Ruby on Rails app? Need a way to allow for multiple keys with the same name and without any namespace clashing or loss of data.

    Read the article

  • Ruby efficient way of building an array from an array of arrays

    - by randombits
    I have an array of ActiveRecord objects, each one which has its own respective errors array. I want to flatten it all out and get only the unique values into one array. So the top level array might look like: foo0 = Foo.new foo1 = Foo.new foo2 = Foo.new foo3 = Foo.new arr = [foo0, foo1, foo2, foo3] Each one of those objects could potentially have an array of errors, and I'd like to get just the unique message out of them and put them in another array, say called error_arr. How would you do it the "Ruby" way?

    Read the article

  • Understanding Ruby class vs instance methods

    - by randombits
    I have the following code: #!/usr/bin/ruby class Person def self.speak p = self.new puts "Hello" p.chatter end private def chatter puts "Chattering" end end p = Person.new Person.speak I'd like to make chatter private, accessible only within p.. but I want p to be able to access it within the class method. Is there a better way to design this so chatter isn't available to the public, but a "factory" method like self.speak can call chatter?

    Read the article

  • Rails best practice on conditional parameters in a controller action

    - by randombits
    I have a controller create action looks for one or more parameters in the following ruleset. Let's say we have two parameters, foo and bar. The rules are the following: 1) if foo doesn't exist in the parameter list, bar must. 2) if bar doesn't exist in the parameter list, foo must. 3) they can both co-exist. they can't both be omitted (that's redundant with my rules above :) ) Can anyone show an example in Rails on how this is handled in the controller? Should I use a before_filter? Would appreciate some guidance as this isn't something that ActiveRecord validates.. so I'd need to build an error message to the user directly from controller logic, not model logic. For bonus points, I output the error in XML, so if you can show how that's done, that'd be great. Hypothetically let's call the resource "Lorem", so it is created via http://foo/lorem.xml and we have lorem_controller.rb.

    Read the article

  • Ruby on Rails bizarre behavior with ActiveRecord error handling

    - by randombits
    Can anyone explain why this happens? mybox:$ ruby script/console Loading development environment (Rails 2.3.5) >> foo = Foo.new => #<Foo id: nil, customer_id: nil, created_at: nil, updated_at: nil> >> bar = Bar.new => #<Bar id: nil, bundle_id: nil, alias: nil, real: nil, active: true, list_type: 0, body_record_active: false, created_at: nil, updated_at: nil> >> bar.save => false >> bar.errors.each_full { |msg| puts msg } Real can't be blank Real You must supply a valid email => ["Real can't be blank", "Real You must supply a valid email"] So far that is perfect, that is what i want the error message to read. Now for more: >> foo.bars << bar => [#<Bar id: nil, bundle_id: nil, alias: nil, real: nil, active: true, list_type: 0, body_record_active: false, created_at: nil, updated_at: nil>] >> foo.save => false >> foo.errors.to_xml => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>\n <error>Bars is invalid</error>\n</errors>\n" That is what I can't figure out. Why am I getting Bars is invalid versus the error messages displayed above, ["Real can't be blank", "Real you must supply a valid email"] etc. My controller simply has a respond_to method with the following in it: format.xml { render :xml => @foo.errors, :status => :unprocessable_entity } How do I have this output the real error messages so the user has some insight into what they did wrong?

    Read the article

  • Rails 2.3: How to create this SQL into a named_scope

    - by randombits
    Having a bit of difficulty figuring out how to create a named_scope from this SQL query: select * from foo where id NOT IN (select foo_id from bar) AND foo.category = ? ORDER BY RAND() LIMIT 1; Category should be variable to change. What's the most efficient way the named_scope can be written for the problem above?

    Read the article

  • Add foreign key constraints to existing tables in Ruby on Rails (MySQL)

    - by randombits
    What's the best way to add foreign keys to my existing tables in Rails with an underlying MySQL database? clearly the solution should be done in a migration, as I want this versioned. Otherwise I'd create the constraints myself. I can't seem to find one, conducive response to they above. Again, the tables have already been created with previous migrations. I'm just going back now and adding referential integrity wherever it's applicable.

    Read the article

  • Breakdown of this Ruby code?

    - by randombits
    Would anyone be kind enough to dissect the merge! method? Its usage of conditions and variable assignment looks rather terse, and I'm having a difficult time following it. Would love to hear a Ruby-savvy developer break this apart. module ActiveRecord class Errors def merge!(errors, options={}) fields_to_merge = if only=options[:only] only elsif except=options[:except] except = [except] unless except.is_a?(Array) except.map!(&:to_sym) errors.entries.map(&:first).select do |field| !except.include?(field.to_sym) end else errors.entries.map(&:first) end fields_to_merge = [fields_to_merge] unless fields_to_merge.is_a?(Array) fields_to_merge.map!(&:to_sym) errors.entries.each do |field, msg| add field, msg if fields_to_merge.include?(field.to_sym) end end end end

    Read the article

  • Running Rails as an embedded app inside of a gem

    - by randombits
    I'm trying to understand what exactly the above (in my question's Title) means? This is taken directly from the SpreeCommerce.com project: If you’re an experienced Rails developer you may be wondering where your app directory is. Spree actually runs as an embedded Rails app inside of your gem. How do you customize things then? We’ll cover that later in extensions. Source: http://spreecommerce.com/documentation/getting_started.html Can someone further explain what exactly it means when a Rails app is run "inside of your gem"

    Read the article

  • iPhone: Does it ever make sense for an object to retain its delegate?

    - by randombits
    According to the rules of memory management in a non garbage collected world, one is not supposed to retain a the calling object in a delegate. Scenario goes like this: I have a class that inherits from UITableViewController and contains a search bar. I run expensive search operations in a secondary thread. This is all done with an NSOperationQueue and subclasses NSOperation instances. I pass the controller as a delegate that adheres to a callback protocol into the NSOperation. There are edge cases when the application crashes because once an item is selected from the UITableViewController, I dismiss it and thus its retain count goes to 0 and dealloc gets invoked on it. The delegate didn't get to send its message in time as the results are being passed at about the same time the dealloc happens. Should I design this differently? Should I call retain on my controller from the delegate to ensure it exists until the NSOperation itself is dealloc'd? Will this cause a memory leak? Right now if I put a retain on the controller, the crashes goes away. I don't want to leak memory though and need to understand if there are cases where retaining the delegate makes sense. Just to recap. UITableViewController creates an NSOperationQueue and NSOperation that gets embedded into the queue. The UITableViewController passes itself as a delegate to NSOperation. NSOperation calls a method on UITableViewController when it's ready. If I retain the UITableViewController, I guarantee it's there, but I'm not sure if I'm leaking memory. If I only use an assign property, edge cases occur where the UITableViewController gets dealloc'd and objc_msgSend() gets called on an object that doesn't exist in memory and a crash is imminent.

    Read the article

  • Ruby on Rails: building a model with an attribute not in the database?

    - by randombits
    I have a model that sets one of its attributes based off of a form parameter that a user submits. The model is a child resource to a parent resource Home. A hypothetical example is the following: A class Person has an age attribute. The user submits a birthdate as an HTTP POST parameter and from that, I need to derive the age of the user. So I'd do something like this: @home.people.build(:name => params[:name], :birthdate => params[:birthdate]) Rails would barf on that for obvious reasons, complaining it doesn't know what the attribute birthdate is. What's the proper way of going about this? Is it possible to use the build constructor with the supplied solution so that my foreign key relations are also setup properly? If not, what's a better way to work around this problem?

    Read the article

  • Catching an error for a child resource in Ruby on Rails

    - by randombits
    What is the best way to add errors to render if a child resource is really what's having issues and not the parent resource? In english what I mean is the following.. imagine the following code: @foo = Foo.new foochild = Foochild.new // break foochild somehow @foo << foochild @foo.save now when I do: format.xml { render :xml => @foo.errors } I don't get anything about how foochild broke, meaning the error message is useless to the user. How does one go about fixing this?

    Read the article

  • Python: Taking an array and break it into subarrays based on some criteria

    - by randombits
    I have an array of files. I'd like to be able to break that array down into one array with multiple subarrays, each subarray contains files that were created on the same day. So right now if the array contains files from March 1 - March 31, I'd like to have an array with 31 subarrays (assuming there is at least 1 file for each day). In the long run, I'm trying to find the file from each day with the latest creation/modification time. If there is a way to bundle that into the iterations that are required above to save some CPU cycles, that would be even more ideal. Then I'd have one flat array with 31 files, one for each day, for the latest file created on each individual day.

    Read the article

  • How to handle this type of model validation in Ruby on Rails

    - by randombits
    I have a controller/model hypothetically named Pets. Pets has the following declarations: :belongs_to owner :has_many dogs :has_many cats Not the best example, but again, it demonstrates what I'm trying to solve. Now when a request comes in as an HTTP POST to http://127.0.0.1/pets, I want to create an instance of Pets. The restriction here is, if the user doesn't submit at least one dog or one cat, it should fail validation. It can have both, but it can't be missing both. How does one handle this in Ruby on Rails? Dogs don't care if cats exists and the inverse is also true. Can anyone show some example code of what the Pets model would look like to ensure that one or the other exists, or fail otherwise? errors.add also takes an attribute, in this case, there is no particular attribute that's failing. It's almost a 'virtual' combination that's missing.

    Read the article

  • Resource mapping in a Ruby on Rails URL (RESTful API)

    - by randombits
    I'm having a bit of difficulty coming up with the right answer to this, so I will solicit my problem here. I'm working on a RESTFul API. Naturally, I have multiple resources, some of which consist of parent to child relationships, some of which are stand alone resources. Where I'm having a bit of difficulty is figuring out how to make things easier for the folks who will be building clients against my API. The situation is this. Hypothetically I have a 'Street' resource. Each street has multiple homes. So Street :has_many to Homes and Homes :belongs_to Street. If a user wants to request an HTTP GET on a specific home resource, the following should work: http://mymap/streets/5/homes/10 That allows a user to get information for a home with the id 10. Straight forward. My question is, am I breaking the rules of the book by giving the user access to: http://mymap/homes/10 Technically that home resource exists on its own without the street. It makes sense that it exists as its own entity without an encapsulating street, even though business logic says otherwise. What's the best way to handle this?

    Read the article

  • Add a foreign key to existing tables in Rails (MySQL)

    - by randombits
    What's the best way to add foreign keys to my existing tables in Rails with an underlying MySQL database? clearly the solution should be done in a migration, as I want this versioned. Otherwise I'd create the constraints myself. I can't seem to find one, conducive response to they above. Again, the tables have already been created with previous migrations. I'm just going back now and adding referential integrity wherever it's applicable.

    Read the article

  • Retrieving a unique result set with Core Data

    - by randombits
    I have a core data based app that manages a bunch of entities. I'm looking to be able to do the following. I have an entity "SomeEntity" with the attributes: name, type, rank, foo1, foo2. Now, SomeEntity has several rows if when we're speaking strictly in SQL terms. What I'm trying to accomplish is to retrieve only available types, even though each instance can have duplicate types. I also need them returned in order according to rank. So in SQL, what I'm looking for is the following: SELECT DISTINCT(type) ORDER BY rank ASC Here is the code I have so far that's breaking: NSError *error = NULL; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setReturnsDistinctResults:YES]; [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"type", @"rank", nil]]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"SomeEntity" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // sort by rank NSSortDescriptor *rankDescriptor = [[NSSortDescriptor alloc] initWithKey:@"rank" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:rankDescriptor,nil]; [fetchRequest setSortDescriptors:sortDescriptors]; [sortDescriptors release]; [rankDescriptor release]; NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; [fetchRequest release]; return fetchResults; Right now that is crashing with the following: Invalid keypath section passed to setPropertiesToFetch:

    Read the article

  • Possible to see what actual SQL queries Rails invokes when using console script?

    - by randombits
    Sometimes I like to pop open the console script that comes with Rails to test small excerpts of code. That code normally involves some more involved ActiveRecord queries. Although not an expert in ActiveRecord, I'm proficient with SQL and want to see what it's translating underneath the hood for efficiency purposes. This will help me refactor or rethink how I'm writing my app if it looks inefficient. Now when the query is in the actual application itself, it all shows up in logs. Ad-hoc ActiveRecord queries in the console do not though. Anyway to change that behavior?

    Read the article

< Previous Page | 1 2 3  | Next Page >