#StackBounty: #ruby #ruby-on-rails #join #active-record Update join table using list of checkboxes in Rails

Bounty: 50

I have Gig and Singer Active Record models (standard–no customization just yet) with a many-to-many relationship through a generic join table which holds nothing but the respective ids of Gig and Singer. My form sends a given gig id and all the singers who will be attending, denoted with check boxes. I need to have the ability to check or uncheck singers. The following code works, but it does so by removing all the singers from a gig and re-adding them. This feels hacky… is there a better way? (I think this is all the code necessary but let me know if you need me to add anything)

class GigSingersController < ApplicationController

    def create
        gig = Gig.find(params[:gig_id])
        singer_ids = params[:singer_ids] # [1, 4, 5,]
        gig.singers = []
        singer_ids.each do |id|
            singer = Singer.find(id)
            gig.singers << singer
        redirect_to gigs_path


As requested in the comments, here are the schema and relevant models, although as I said, they are completely generic. Perhaps I didn’t do a good job of making my question clear: Is the best way to create these relationships when using a checkbox to remove all existing ones and recreate them from the boxes currently checked, thereby removing any that the user unchecked on an edit?

ActiveRecord::Schema.define(version: 2019_07_19_195106) do

  create_table "gig_singers", force: :cascade do |t|
    t.integer "gig_id"
    t.integer "singer_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false

  create_table "gigs", force: :cascade do |t|
    t.string "name"
    t.text "notes"
    t.datetime "datetime"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false

  create_table "singers", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.boolean "active"

class Gig < ApplicationRecord
    has_many :gig_singers
    has_many :singers, through: :gig_singers

class GigSinger < ApplicationRecord
    belongs_to :gig
    belongs_to :singer

class Singer < ApplicationRecord
    has_many :gig_singers
    has_many :gigs, through: :gig_singers


Get this bounty!!!

#StackBounty: #ruby #ruby-on-rails-4 #woocommerce #wordpress-rest-api #woocommerce-rest-api Creating coupon through API and ruby return…

Bounty: 50

I am trying to create a coupon though the rest api from my rails 4 app using the sample code from the documentation on this page: https://woocommerce.github.io/woocommerce-rest-api-docs/?ruby#create-a-coupon

Here is the code I am using:

data = {
code: “10off”,
discount_type: “percent”,
amount: “10”,
individual_use: true,
exclude_sale_items: true,
minimum_amount: “100.00”

woocommerce.post("coupons", data).parsed_response

I expect it to return a successful response from the API instead I get {“errors”=>[{“code”=>”woocommerce_api_missing_coupon_data”, “message”=>”No coupon data specified to create coupon”}]}

Get this bounty!!!

#StackBounty: #ruby-on-rails #ruby #amp-html Headers setting for AMP form in Rails

Bounty: 300

My AMP form in Rails is returning this error in the terminal :

Completed 406 Not Acceptable in 338ms (ActiveRecord: 54.1ms)
ActionController::UnknownFormat (InscriptionsController#create is missing a template for this request format and variant.
request.formats: ["application/json"]
request.variant: []):

And in the browser :

POST http://localhost:3000/inscriptions?__amp_source_origin=http%3A%2F%2Flocalhost%3A3000 406 (Not Acceptable)
Response must contain the AMP-Access-Control-Allow-Source-Origin header
Form submission failed: Error: Response must contain the AMP-Access-Control-Allow-Source-Origin header​​​
at bb.f.assert (https://cdn.ampproject.org/v0.js:21:319)
at y (https://cdn.ampproject.org/v0.js:26:213)
at https://cdn.ampproject.org/v0.js:179:339

However I did follow the CORS sample code provided by the official documentation https://amp.dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/amp-cors-requests?referrer=ampproject.org, and according to the AMP validation, everything is fine,

This is my controller :

def create
  @inscription = Inscription.new(inscription_params)
  subscriber_email = inscription_params[:email].downcase
  if Subscriber.where(email: subscriber_email).count == 0
    @subscriber = Subscriber.new
    @subscriber.email = subscriber_email
    @new_subscriber = true
    @subscriber = Subscriber.where(email: subscriber_email).first
    @new_subscriber = false
 respond_to do |format|
  format.html { redirect_to root_path, notice: "Merci ! Nous avons bien reçu votre inscription !" }
  format.json {
    allowed_origins = ["https://example.com", "https://example.com.cdn.ampproject.org/", "http://example.com.amp.cloudflare.com", "https://cdn.ampproject.org"]
    allowed_source_origin = "https://example.com"
    source_origin = params[:__amp_source_origin]
    origin = request.headers["Origin"]
    response.set_header('Content-type', 'application/json')
    response.set_header('Access-Control-Allow-Credentials', 'true')
    response.set_header('Access-Control-Allow-Origin', origin)
    response.set_header('AMP-Access-Control-Allow-Source-Origin', source_origin)
    p response.headers

May you help me with this ? I probably did something wrong with the headers. Thanks a lot !

Get this bounty!!!

#StackBounty: #ruby #geocoding Offline reverse geocoding at country level [(lat, lon) to country] for Ruby

Bounty: 50

I am looking for offline geocoder that would

  • locate country where specific point is located
  • be usable in a Ruby script
  • work offline (required due to a high number of points)
  • is using OpenStreetMap data or other on a compatible license
  • accurate, objects hundreds meters from country border should be also correctly located

I am fine with some setup. Limited performance is also OK, number of processed entries is not massive and I am fine with script running for week or two.

Note that I am fully aware about number of geocoding APIs, I am currently using one but I need something that works offline.

Get this bounty!!!

#StackBounty: #ruby-on-rails #ruby #web-services #httpclient #httparty Send multiple files using HTTParty

Bounty: 50

Here is the code which is working using Net::HTTP::Post

request = Net::HTTP::Post.new(url)
form_data = [
  ['attachments[]', File.open('file1.txt')],
  ['attachments[]', File.open('file2.txt')]
request.set_form form_data, 'multipart/form-data'

Now, I am trying to use httparty like below but it is not working.

body = { attachments: [ File.open('file1.txt'), File.open('file2.txt') ] }

HTTParty.post(url, body: body)

The response I am getting from web service call is below:

#<HTTParty::Response:0x557d7b549f90 parsed_response={"error"=>true, "error_code"=>"invalid_attachment", "error_message"=>"Attachmen
t(s) not found or invalid."}, @response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, @headers={"server"=>["nginx"], "date"=>[
"Mon, 20 May 2019 07:41:50 GMT"], "content-type"=>["application/json"], "content-length"=>["102"], "connection"=>["close"], "vary"=>["
Authorization"], "set-cookie"=>["c18664e1c22ce71c0c91742fbeaaa863=uv425hihrbdatsql1udrlbs9as; path=/"], "expires"=>["Thu, 19 Nov 1981
08:52:00 GMT", "-1"], "cache-control"=>["no-store, no-cache, must-revalidate", "private, must-revalidate"], "pragma"=>["no-cache", "no
-cache"], "x-ratelimit-limit"=>["60"], "x-ratelimit-remaining"=>["59"], "strict-transport-security"=>["max-age=63072000; includeSubdom

It looks like it is not able to read the contents of files. Does HTTParty supports this or I need to use some other gem?

Get this bounty!!!

#StackBounty: #c #ruby #ffi creating a Dynamic array class in ruby using FFI and C function

Bounty: 50

I would like to create my own dynamic array class in ruby (as a training).
The idea is to have a class DynamicArray that has a capacity (the number of elements it can hold at one given moment), a size (the number of elements that were actually pushed in the array at a given moment) and a static_array which is a static array of ints of a fixed sized. Whenever this static_array is full, we will create a new static array with twice the capacity of the original static_array and copy every elements inside the new static_array.
As there is no static array in ruby, my idea was to use FFI https://github.com/ffi/ffi. to create a function in c that creates a static array of int of size n then be able to use it in my ruby program.
I have very little knowledge in C and am having a hard time understanding the doc of FFI
Here’s what I have so far, a create_array.c file that defines my c function to create an array.

int * createArray ( int size )
  int array[size];
  return 0;


a create_array.h file (from what I understood of FFI, you need to put your c functions in a c library.):

int * createArray ( int size )

and this is my dynamic_array.rb file that would do something along this lines :

require 'ffi'
class DynamicArray
  extend FFI::Library
  ffi_lib "./create_array.h"
  attach_function :create_array, [:int], :int
  def initialize
    @size = 0
    @capacity = 1
    @current_index = 0
    @static_array = create_array(@capacity)

  def add(element)
    @size += 1
    resize_array if @size > @capacity
    @static_array[@current_index] = element
    @current_index += 1


  def resize_array
    @capacity = @capacity*2
    new_arr = create_array(@capacity)
    @static_array.each_with_index do |val, index|
      new_arr[index] = val
    @static_array = new_arr

Here are some tests for add and resize :

  def test_add
    dynamic_arr = DynamicArray.new
    assert_equal(1, dynamic_arr.static_array[0])
    assert_equal(2, dynamic_arr.static_array[1])

  def test_resize_array
    dynamic_arr = DynamicArray.new
    assert_equal(2, dynamic_arr.capacity)
    assert_equal(4, dynamic_arr.capacity)

Can you please explain me what I should do to make this work ?

Get this bounty!!!

#StackBounty: #ruby-on-rails #ruby #ruby-on-rails-5 #monkeypatching #rails-activestorage Monkey patching ActiveStorage::Attachment gets…

Bounty: 50

So I decided to add an url attr_accessor to ActiveStorage::Attachment objects.

In development the patch holds for a while until it seems to “have been lost”. Meaning it works for few minutes, then it does not work anymore. Then I need to restart the server in order to get the patch applied again. I believe I am not patching correctly and I would need advises in that mater.

Here is what I tried:


First try :

module ActiveStorageUrl
  extend ActiveSupport::Concern

  included do
    attr_accessor :url

ActiveStorage::Attachment.send :include, ActiveStorageUrl

Second try

class ActiveStorage::Attachment < ActiveRecord::Base
  attr_accessor :url

And by the way in both case it’s loaded with this:


require 'ext/active_storage/attachment'

So when it work I have no error message, but after a while the patch “diseapear” (lacking better terms), and I get the following error, telling me my attr_accessor is not there anymore. Rails must have reloaded ActiveStorage classes and my patch is lost.

Module::DelegationError in Products#images
url delegated to blob, but blob is nil

Get this bounty!!!