Git Product home page Git Product logo

airtable-ruby's Introduction

Airtable Ruby Client

Easily connect to airtable data using ruby with access to all of the airtable features.

Note on library status

We are currently transitioning this gem to be supported by Airtable. We will maintain it moving forward, but until we fully support it, it will stay in the status of "community libraries". At that time we will remove this notice and add a "ruby" section to the API docs.

Installation

Add this line to your application's Gemfile:

gem 'airtable'

And then execute:

$ bundle

Or install it yourself as:

$ gem install airtable

Usage

Creating a Client

First, be sure to register for an airtable account, create a data worksheet and get an api key. Now, setup your Airtable client:

# Pass in api key to client
@client = Airtable::Client.new("keyPCx5W")

Your API key carries the same privileges as your user account, so be sure to keep it secret!

Accessing a Table

Now we can access any table in our Airsheet account by referencing the API docs:

# Pass in the app key and table name
@table = @client.table("appPo84QuCy2BPgLk", "Table Name")

Querying Records

Once you have access to a table from above, we can query a set of records in the table with:

@records = @table.records

We can specify a sort order, limit, and offset as part of our query:

@records = @table.records(:sort => ["Name", :asc], :limit => 50)
@records # => [#<Airtable::Record :name=>"Bill Lowry", :email=>"[email protected]">, ...]
@records.offset #=> "itrEN2TCbrcSN2BMs"

This will return the records based on the query as well as an offset for the next round of records. We can then access the contents of any record:

@bill = @record.first
# => #<Airtable::Record :name=>"Bill Lowry", :email=>"[email protected]", :id=>"rec02sKGVIzU65eV1">
@bill[:id] # => "rec02sKGVIzU65eV2"
@bill[:name] # => "Bill Lowry"
@bill[:email] # => "[email protected]"

Note that you can only request a maximimum of 100 records in a single query. To retrieve more records, use the "batch" feature below.

Batch Querying All Records

We can also query all records in the table through a series of batch requests with:

@records = @table.all(:sort => ["Name", :asc])

This executes a variable number of network requests (100 records per batch) to retrieve all records in a sheet.

We can also use select method to query based on specific conditions using formula parameter

@records = @table.select(sort: ["Order", "asc"], formula: "Active = 1")

This will return all the records that has Active column value as true from table.

Finding a Record

Records can be queried by id using the find method on a table:

@record = @table.find("rec02sKGVIzU65eV2")
# => #<Airtable::Record :name=>"Bill Lowry", :email=>"[email protected]", :id=>"rec02sKGVIzU65eV1">

Inserting Records

Records can be inserted using the create method on a table:

@record = Airtable::Record.new(:name => "Sarah Jaine", :email => "[email protected]")
@table.create(@record)
# => #<Airtable::Record :name=>"Sarah Jaine", :email=>"[email protected]", :id=>"rec03sKOVIzU65eV4">

Updating Records

Records can be updated using the update method on a table:

@record[:email] = "[email protected]"
@table.update(record)
# => #<Airtable::Record :name=>"Sarah Jaine", :email=>"[email protected]", :id=>"rec03sKOVIzU65eV4">

Deleting Records

Records can be destroyed using the destroy method on a table:

@table.destroy(record)

Contributing

  1. Fork it ( https://github.com/nesquena/airtable-ruby/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

airtable-ruby's People

Contributors

chug2k avatar nesquena avatar rohandaxini avatar sirupsen avatar syrnick avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

airtable-ruby's Issues

Update won't work with formula/lookup fields in the table

Hi,

I was having a ton of problems getting an existing record to update, and then I found this line in lib/airtable/records.rb:

# Airtable will complain if we pass an 'id' as part of the request body.
def fields_for_update; fields.except(:id); end

It turns out that Airtable will complain if you've got any calculated fields in the table, and it won't update :/

What I've done to fix this in my code is a monkeypatch like this:

module Airtable
  class Record
    def fields_for_update
      fields.except(:id, :FormulaField, :LookupField)
    end
  end
end

... but I wonder if there's a more elegant way to do this?

The most elegant way to fix it would be if Airtable didn't FAIL when you try to update a calculated field (or the ID), but merely sent along some kind of warning. I'll send this idea along to them as well.

Thanks!
-Donald

cannot connect to airtable

I try to acces all records of my airtable. The following returns an empty array, although i checked API key and appId and table name multiple times. What else could be the issue?

@client = Airtable::Client.new(ENV['AIRTABLE_API_KEY'])
@table = @client.table("app....", "My Table Name")
@records = @table.records

I read that this repo is not maintained, is that maybe the reason why it doesnt work?

Deleting records - error in the example

Just a heads up: your example in README.md is wrong on deleting records:
@table.destroy(record)

It should be
@table.destroy(record_id)
or something similar, to show that the id is needed, not the whole record...

Banged my head to the wall about this for a while until I went to the code and checked.

Record creation fails

I am currently able to create an empty record (which is seen in Airtable by a new empty row) with
@record = Airtable::Record.new()
@table.create(@record)

but whenever I try to create a record with some predefined keys as in your example

@record = Airtable::Record.new(:name => "Sarah Jaine", :email => "[email protected]")
@table.create(@record)

(Of course I am using my own column names...)

nothing at all gets created. Documentation is very minimalistic, so: does the record need to include all the keys? Any idea why my record creation with any real values fails?

I get no Ruby errors, but nothing gets created.

Create / Update failing silently

Hi,

I'm on version 0.0.9. I am finding that I can access the table data via the all and records methods, however, when I try create or update the methods just return false. It's not out of the realms of possibility that I'm doing something wrong but the response is very opaque so it's hard to find out. It's not obvious from the code what could cause this failure mode, but I only see version 0.0.8 in this repo... Any clues on what could be going wrong, or how to debug further?

Regards,
Imran

uninitialized constant Airtable::Record::HashWithIndifferentAccess

Hi,

I've been working on getting this gem to work for some time, and I'm stuck. I'm wondering if the issue is my setup or the gem.

Here's my setup code:

#!/usr/bin/env ruby

require 'airtable'

at_key = 'KEY_REDACTED'
at_base = 'BASE_REDACTED'

@client = Airtable::Client.new(at_key)
@table = @client.table(at_base, "Videos")
@records = @table.records
p @records.inspect

...pretty much straight from the README. When I run that code, I get this error:

/Users/donald/.rbenv/versions/1.9.3-p551/lib/ruby/gems/1.9.1/gems/airtable-0.0.8/lib/airtable/record.rb:33:in override_attributes!': uninitialized constant Airtable::Record::HashWithIndifferentAccess (NameError) from /Users/donald/.rbenv/versions/1.9.3-p551/lib/ruby/gems/1.9.1/gems/airtable-0.0.8/lib/airtable/record.rb:5:ininitialize'
from /Users/donald/.rbenv/versions/1.9.3-p551/lib/ruby/gems/1.9.1/gems/airtable-0.0.8/lib/airtable/record_set.rb:13:in new' from /Users/donald/.rbenv/versions/1.9.3-p551/lib/ruby/gems/1.9.1/gems/airtable-0.0.8/lib/airtable/record_set.rb:13:inblock in initialize'
from /Users/donald/.rbenv/versions/1.9.3-p551/lib/ruby/gems/1.9.1/gems/airtable-0.0.8/lib/airtable/record_set.rb:13:in map' from /Users/donald/.rbenv/versions/1.9.3-p551/lib/ruby/gems/1.9.1/gems/airtable-0.0.8/lib/airtable/record_set.rb:13:ininitialize'
from /Users/donald/.rbenv/versions/1.9.3-p551/lib/ruby/gems/1.9.1/gems/airtable-0.0.8/lib/airtable/table.rb:27:in new' from /Users/donald/.rbenv/versions/1.9.3-p551/lib/ruby/gems/1.9.1/gems/airtable-0.0.8/lib/airtable/table.rb:27:inrecords'
from ./gem_test.rb:10:in `<

As you can see, I'm using rbenv. I've run this same code on Ruby 1.9.1, 2.2.4, and 2.3.0 and I can't get it to do anything but give me the error you see above. Am I missing something? Or this this a bug?

I downloaded the gem source to my machine and ran the tests, which ran just fine.

Bump to 0.10 on rubygems.org

Can you bump to 0.10 on rubygems.org? I need to leverage the escaping in the URI request, but don't want to point directly to github.

0.0.9 release

I'm working on a gem that needs 0.0.9's Airtable::Table.update_record_fields method. Could you publish 0.0.9 to RubyGems please?

FWIW, here's the gem I'm working on: https://github.com/chrisfrank/airmodel

It currently monkeypatches airtable-ruby 0.0.8 with your update_record_fields method, but I'd like to remove that code from my gem as soon as I can. Thanks!

Table names with embedded space characters are incorrectly escaped.

In the protected method, worksheet_url in table.rb the CGI.escape method is called to escape special characters in the url. The problem is that this method replaces space characters with a '+' rather than %20. The '+' would be correct for url parameters but is not correct for spaces in the url path.

Possible fixes:

  1. Change to CGI.escape(s).gsub('+','%20')
  2. Remove it altogether and leave it up to the user to make sure spaces are escaped correctly.

Add support for searching

This is more of a heads up that we pushed out new API capabilities. Airtable/airtable.js@08e6e76

We now accept a formula to filter records and an array of fields/direction pairs to sort by.

The limit is deprecated in favor of pageSize and maxRecords.

MAINTAINER needed

This gem needs a bit of TLC. Looking for the right person to do it.

It's not a lot of work, but it's a bit, plus likely ongoing maintenance: mostly addressing all the issues, some refactoring and solid test coverage.

If you're interested, email alex AT airtable .com for more detailed scope.

0.0.9 breaks spaces

Recently we updated to version 0.0.9 and noticed that tables with spaces do not work anymore.

I am not sure why version 0.0.9 was released to ruby gems but is not under releases here on github.

The problems seems to be the following line: 924c6c5#diff-e66b30ad5f17164353db64687091edd3R96

URI.encode("Hello World")
=> "Hello%20World"
CGI.escape("Hello World")
=> "Hello+World"

Sascha

Remove "column_keys" from output

I've successfully used the plugin to fetch data and write it to a json file (despite knowing nothing about ruby) but I'm at a loss as to how to parse the headers out of the json so I can consume it with jekyll.

The json I'm getting looks like this

[{"column_keys":["title","gallery","event","ministry","published","date_added","ministry_name","ten_minutes","id"],"attrs":{"title":"Family Revival","gallery":[{"id":"attcNc5ihYUtR3QdD","url":"https://dl.airtable.com/BarsFKuSvKRea5cOgHs5_IMG_3174.jpg","filename":"IMG_3174.jpg","size":2042172,"type":"image/jpeg","thumbnails":{"small":{"url":"https://dl.airtable.com/nsv6C5TACt49UdktTNEg_small_IMG_3174.jpg","width":48,"height":36},"large":{"url":"https://dl.airtable.com/JNh8Z65SIaQb6V2Fgc4d_large_IMG_3174.jpg","width":512,"height":512}}}

And on and on and on (it's a very long file.)
The json I'm used to getting (from the node client) looks like this:

[{"title":"Family Revival","gallery":[{"id":"attcNc5ihYUtR3QdD","url":"https://dl.airtable.com/BarsFKuSvKRea5cOgHs5_IMG_3174.jpg","filename":"IMG_3174.jpg",

And my ruby script looks like this:

require 'json'
require 'airtable'
require 'active_support/all'

# Pass in api key to client
@client = Airtable::Client.new("key...")
# Pass in the app key and table name
@table = @client.table("app...", "Photos")
@records = @table.records(:sort => ["date_added", :desc], :limit => 50)

File.open("_data/photos.json", "w") do |f|
    f.write(@records.to_json)
end 

Obviously I need to do something to the ruby script to strip that initial json, but what?

Sort by Multiple Columns

Hi,

Looking at the API docs, it seems that Airtable should be able to support sorting via multiple columns via the API:

A list of sort objects that specifies how the records will be ordered. Each sort object must have a field key specifying the name of the field to sort on, and an optional direction key that is either "asc" or "desc". The default direction is "asc".

But I'm noticing that the records method (among others) in lib/airtable/table.rb seems to hard-code sort at one parameter:

    def records(options={})
      options["sortField"], options["sortDirection"] = options.delete(:sort) if options[:sort]
      results = self.class.get(worksheet_url, query: options).parsed_response
      RecordSet.new(results)
    end

I've tried simply commenting out the first line of that method and passing my own sort object (ie sort: [{field: 'fieldName', direction: :asc}], but likely due to my unfamiliarity with HTTParty or the Airtable API, I can't figure out how to pass multiple sort objects through the records method.

Basically: I would have submitted a pull request to adjust this method to allow multiple sort, but I can't figure it out :/ Hopefully you know more than me on the topic.

Thanks!

Wondering how to do filterByFormula

I've spent a lot of time with the Node version of this, and I'm wondering if there is a way to do filterByFormula. A simple example would be really nice.

For instance, I'm wondering if there is something like this:

@table = @client.table("MyAppID", "Movies")
@records = @table.records(:sort => ["weekend_at", :desc], :limit => 100, :filterByFormula => 'Live')

Thanks in advance

Formula Lookup needs documentation

So I wrote this functionality and I have no idea how to use it.

I've been trying to use https://support.airtable.com/hc/en-us/articles/203255215-Formula-Field-Reference but it really isn't all that helpful.

For instance, I wanted to select only the records where a boolean column is true. For the formula string supplied to select I tried

approved = true
Approved = true
Approved IS true
TRUE(Approved)

until I landed, with a wild guess, on Approved = 1 which worked.

I'm happy to help document this, but I feel like I don't have enough knowledge about Airtable's code base to really do it accurately.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.