Sunday, September 11, 2016

How can I see my uploaded images? | Fixed issues

How can I see my uploaded images? | Fixed issues


How can I see my uploaded images?

Posted: 11 Sep 2016 07:50 AM PDT

Ruby version 2.2.4 Rails version 5.0.0.1

Hello people

I am a totally beginner in RoR and after long hours I finally uploaded an picture from my android app to ruby on rails. I have the code from a tutorial which provides the upload function. However the function how you can see the picture is missed. How can I implement this in ruby on rails? I want to see the pictures in a table

Here is what I have so far

enter image description here

And here is the code: views/items/inde.html.erb

h1>Rails-API-Fileupload-tutorial-Cariierwave-Single</h1>  <h2>Listing documents</h2>    <table>    <thead>      <tr>        <th>Filename</th>        <th></th>        <th></th>      </tr>    </thead>      <tbody>      <% @items.each do |item| %>        <tr>          <td><%= item.id %></td>          <td><%= item%></td>        </tr>      <% end %>    </tbody>  </table>    <br>  

routes.rb

Rails.application.routes.draw do    resources :items, :pictues      root to: redirect('/items')      post  to: 'items'  end  

Digitalocean ROR app deploy 500 error. How to see server logs?

Posted: 11 Sep 2016 07:29 AM PDT

I have deployed my rails app via https://www.digitalocean.com/community/tutorials/how-to-use-the-ruby-on-rails-one-click-application-on-digitalocean tutorial. But my app returns a 500 internal server error.

How to see server logs? When I start local server on localhost I can see live server logs, how to enable it on digitalocean? Any ideas?

Deploying to heroku - failed to detect buildpack nodejs (jasonswett)

Posted: 11 Sep 2016 07:22 AM PDT

I'm following the tutorial from the book 'Angular for Rails Developers' by Jason Swett. The topic is in chapter 2: Deployment.

First I did this:

$ rm -rf public  $ ln -s client/dist public  

Then after creating the app in heroku, I added the buildpacks

$ heroku buildpacks:add https://github.com/jasonswett/heroku-buildpack-nodejs  $ heroku buildpacks:add heroku/ruby  

Here are the results of the builpacks

=== author-wizard Buildpack URLs  1. https://github.com/jasonswett/heroku-buildpack-nodejs  2. heroku/ruby  

This is the package.json file

{        "name": "author-wizard",        "version": "0.0.0",        "license": "MIT",        "angular-cli": {},        "scripts": {          "start": "ng server",          "postinstall": "typings install && ng build",          "lint": "tslint \"src/**/*.ts\"",          "format": "clang-format -i -style=file --glob=src/**/*.ts",          "pree2e": "webdriver-manager update",          "e2e": "protractor"        },        "private": true,        "dependencies": {          "@angular/common": "2.0.0-rc.1",          "@angular/compiler": "2.0.0-rc.1",          "@angular/core": "2.0.0-rc.1",          "@angular/platform-browser": "2.0.0-rc.1",          "@angular/platform-browser-dynamic": "2.0.0-rc.1",          "@angular/router": "2.0.0-rc.1",          "es6-shim": "^0.35.0",          "reflect-metadata": "0.1.3",          "rxjs": "5.0.0-beta.6",          "systemjs": "0.19.26",          "zone.js": "^0.6.12",          "angular-cli": "0.0.*",          "clang-format": "^1.0.35",          "codelyzer": "0.0.14",          "ember-cli-inject-live-reload": "^1.4.0",          "jasmine-core": "^2.4.1",          "jasmine-spec-reporter": "^2.4.0",          "karma": "^0.13.15",          "karma-chrome-launcher": "^0.2.3",          "karma-jasmine": "^0.3.8",          "protractor": "^3.3.0",          "ts-node": "^0.5.5",          "tslint": "^3.6.0",          "typescript": "^1.8.10",          "typings": "^0.8.1"        },        "devDependencies": {          }      }  

When I pushed to heroku:

$ gp heroku master  Counting objects: 54, done.  Delta compression using up to 4 threads.  Compressing objects: 100% (47/47), done.  Writing objects: 100% (54/54), 11.31 KiB | 0 bytes/s, done.  Total 54 (delta 17), reused 0 (delta 0)  remote: Compressing source files... done.  remote: Building source:  remote:  remote: -----> Failed to detect set buildpack https://github.com/jasonswett/heroku-buildpack-nodejs  remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure  remote:  remote:  !     Push failed  remote: Verifying deploy...  remote:  remote: !       Push rejected to author-wizard.  remote:  To https://git.heroku.com/author-wizard.git   ! [remote rejected] master -> master (pre-receive hook declined)  error: failed to push some refs to 'https://git.heroku.com/author-wizard.git'  

I would appreciate any help. Thank you.

Rails - Two sign up pages

Posted: 11 Sep 2016 07:14 AM PDT

What do you think would be the best approach to create 2 separate sign up pages, with different fields, beside the email & password ones ? After submitting, one of them should assign the user's role with 'student' and the other one with 'teacher', for example. Any ideas? Thanks!

Ruby on Rails on Mac not generating model

Posted: 11 Sep 2016 06:39 AM PDT

When I type into the terminal rails generate model Message, this comes up in the terminal and there is no model called Messages. What should I do? I am using El Capitan. This is the Picture

Rails 5 application: form and api authentication tutorial?

Posted: 11 Sep 2016 06:25 AM PDT

Are there any good tutorial to create an auth system from scraths with form and api authentication?

I found a lot of tutorial but unfortunately they implement only form based or only api based authentication.

But I would like to build a form and api based. Because for the SEO the server side rendering is important so I can create a registration and login form too. But API based important for a mobile app application.

How can i send a math string from an angular 2 form to rails?

Posted: 11 Sep 2016 06:12 AM PDT

I used this tutorial to integrate ror and angular 2 http://tutorials.pluralsight.com/ruby-ruby-on-rails/react-vs-angular-2-integration-with-rails

but i don't understand how send a math string from an angular 2 form to rails?

You can find code here https://github.com/Kaizeras/rails-angular2starter

How to use Chartkick and mapping line graphs

Posted: 11 Sep 2016 06:11 AM PDT

I am currently using Chartkick to make a line graph that is plotting the progress of a profit and loss chart with individual bets. Currently I have the graph correctly outputting a graph with a profit and loss while the bets are grouped by the day on which they were placed with the following code

<%= area_chart @bets.group(:created_at).sum(:profit_or_loss).map { |x,y| { x => (@sum += y)} }.reduce({}, :merge), xtitle: "Date", ytitle: "Units" %>  

However I am looking to change this so that the graph plots per 50 entries or 100 entries. I am unsure of the correct syntax to group it this way as my understanding is that the id of each entry is not a class.

This is the schema for the entry database.

create_table "bets", force: :cascade do |t|    t.string   "game"    t.datetime "created_at",                            null: false    t.datetime "updated_at",                            null: false    t.string   "bet_placed"    t.decimal  "profit_or_loss", default: 0.0    t.date     "date_of_bet",    default: '2016-03-11'    t.decimal  "odds",           default: 0.0    t.decimal  "units_placed",   default: 0.0    t.boolean  "push",           default: false    t.boolean  "resolved",       default: false    t.integer  "bookmaker"    t.integer  "sport"  end  

Rails 4 Error: ActiveRecord::RecordNotFound Couldn't find 'id'

Posted: 11 Sep 2016 06:24 AM PDT

I'm fairly new to rails and struggling on changing database values after the user successfully paid via stripe. Additionally after paying, it somehow redirects me everytime to '/subscriberjobs/1' where the following error appears. Instead it should direct to the root_path of the application.

This is the appearing error:

ActiveRecord::RecordNotFound in SubscriberjobsController#update  Couldn't find Job with 'id'=  

Here is what I've got:

Routes

resources :subscriberjobs  resources :jobs  

Jobs Controller

def new    if current_user      @job = current_user.jobs.build    else      redirect_to new_user_session_path    end  end  def create    @job = current_user.jobs.build(job_params)      if @job.save      redirect_to "/subscriberjobs/new?job_id=#{@job.id}"    else      render 'new'    end  end  

Subscriberjobs Controller (Here is what doesn't work!)

class SubscriberjobsController < ApplicationController        before_filter :authenticate_user!        def new      end        def update            @job = Job.find(params[:job_id])            token = params[stripeToken]            customer = Stripe::Customer.create(              card: token,              plan: 1004,              email: current_user.email              )            @job.is_active = true          @job.is_featured = false          @job.stripe_id = customer.id          @job.save            redirect_to root_path        end  end  

Form

= simple_form_for @job do |f|      = f.input :company, required: true      = f.input :title, required: true      = f.input :job_filename      = f.input :location, required: true      = f.input :sort      = f.input :tag_list, required: true      = f.input :content_one      = f.input :content_two      = f.input :content_three      = f.hidden_field :job_id, value: params[:id]      = f.button :submit  

Please tell me if you need additional information. Every answer is very appreciated. Thanks!

Ruby on Rails: can not generate url

Posted: 11 Sep 2016 07:23 AM PDT

url generation error Guys, please help. I can't generate the url, don't know what to do. Need your help.

Which rails command creates index.html?

Posted: 11 Sep 2016 05:42 AM PDT

I'm maintaining an old, undocumented rails application. The app/views/application directory has an index.html.haml file, but the public directory doesn't have an index.html file. Which rails command do I need to run to generate the index file in the public directory? I'm using apache as my web server and passenger as my app server.

Guard cannot load bundle/set while spring enabled

Posted: 11 Sep 2016 05:52 AM PDT

Learning Rails by following Rails tutorial, https://www.railstutorial.org/book/static_pages#sec-advanced_testing_setup.

Trying to set up Guard for auto test running but I have the following error when I try to run all tests,

There is NO problem when I turn spring to false.

li-xinyang@MachineX FS_RailsSampleApp (master)*$ bundle exec guard  20:06:46 - INFO - Guard::Minitest 2.4.4 is running, with Minitest::Unit 5.9.0!  20:06:46 - INFO - Guard is now watching at '/Users/li-xinyang/Desktop/FS_RailsSampleApp'  [1] guard(main)>  20:06:53 - INFO - Run all  20:06:53 - INFO - Running: all tests  /usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- bundler/setup (LoadError)      from /usr/local/Cellar/ruby/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/li-xinyang/Desktop/FS_RailsSampleApp/config/boot.rb:3:in `<top (required)>'      from bin/rake:2:in `require_relative'      from bin/rake:2:in `<main>'   

I have tried to kill the spring process and explicitly restart the spring server again, but the error is still there.

The code snippet below is my Gemfile and Guardfile,

source 'https://rubygems.org'    gem 'rails',        '5.0.0.1'  gem 'puma',         '3.4.0'  gem 'sass-rails',   '5.0.6'  gem 'uglifier',     '3.0.0'  gem 'coffee-rails', '4.2.1'  gem 'jquery-rails', '4.1.1'  gem 'turbolinks',   '5.0.1'  gem 'jbuilder',     '2.4.1'    group :development, :test do    gem 'sqlite3', '1.3.11'    gem 'byebug',  '9.0.0', platform: :mri  end    group :development do    gem 'web-console',           '3.1.1'    gem 'listen',                '3.0.8'    gem 'spring',                '1.7.2'    gem 'spring-watcher-listen', '2.0.0'  end    group :test do    gem 'rails-controller-testing', '0.1.1'    gem 'minitest-reporters',       '1.1.9'    gem 'guard',                    '2.13.0'    gem 'guard-minitest',           '2.4.4'  end    group :production do    gem 'pg', '0.18.4'  end    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]  

Guardfile,

# Defines the matching rules for Guard.  guard :minitest, spring: true, all_on_start: false do    watch(%r{^test/(.*)/?(.*)_test\.rb$})    watch('test/test_helper.rb') { 'test' }    watch('config/routes.rb')    { integration_tests }    watch(%r{^app/models/(.*?)\.rb$}) do |matches|      "test/models/#{matches[1]}_test.rb"    end    watch(%r{^app/controllers/(.*?)_controller\.rb$}) do |matches|      resource_tests(matches[1])    end    watch(%r{^app/views/([^/]*?)/.*\.html\.erb$}) do |matches|      ["test/controllers/#{matches[1]}_controller_test.rb"] +      integration_tests(matches[1])    end    watch(%r{^app/helpers/(.*?)_helper\.rb$}) do |matches|      integration_tests(matches[1])    end    watch('app/views/layouts/application.html.erb') do      'test/integration/site_layout_test.rb'    end    watch('app/helpers/sessions_helper.rb') do      integration_tests << 'test/helpers/sessions_helper_test.rb'    end    watch('app/controllers/sessions_controller.rb') do      ['test/controllers/sessions_controller_test.rb',       'test/integration/users_login_test.rb']    end    watch('app/controllers/account_activations_controller.rb') do      'test/integration/users_signup_test.rb'    end    watch(%r{app/views/users/*}) do      resource_tests('users') +      ['test/integration/microposts_interface_test.rb']    end  end    # Returns the integration tests corresponding to the given resource.  def integration_tests(resource = :all)    if resource == :all      Dir["test/integration/*"]    else      Dir["test/integration/#{resource}_*.rb"]    end  end    # Returns the controller tests corresponding to the given resource.  def controller_test(resource)    "test/controllers/#{resource}_controller_test.rb"  end    # Returns all tests for the given resource.  def resource_tests(resource)    integration_tests(resource) << controller_test(resource)  end  

Both files above are copy-paste from the tutorial.

how to make row title a link in active-admin

Posted: 11 Sep 2016 05:08 AM PDT

I am trying to make the title of a row into a link as follow:

attributes_table do    order.order_products_ids.each do |product|      prod = Product.find_by_id(product["product_id"])      row "#{link_to prod.name, [:admin, prod]}" do        panel "Quantity" do          ...        end        ...      end    end  end  

How can I make the line:

row "#{link_to prod.name, [:admin, prod]}" do  

into a link?

The way it is, it is printing the path to the page as:

<A HREF="/ADMIN/PRODUCTS/3">GFHJBKNM</A>  

Rails form won't submit after adding Foundation

Posted: 11 Sep 2016 05:02 AM PDT

I added the Foundation-Rails gem to my app and now my form won't submit. There are no errors in the console, and it's triggering a new event, but instead of adding it to the database, it puts the form submission information into the URL bar. So, it looks like this:

http://localhost:3000/submissions/new?utf8=%E2%9C%93&authenticity_token=T9qweZClsZHL%2B6hzepcz%2BipG4W5p5VEzxO9PcB7FJ%2F6lun8wHVbvtGRe8JZC1rqay5DEMCm%2F06RzQh91G6cRGA%3D%3D&submission%5Bsubmission_link%5D=test&submission%5Blocation%5D=test&submission%5Bbedrooms%5D=0&submission%5Bbathrooms%5D=0&submission%5Bimg1%5D=asdf&submission%5Bimg2%5D=asdf&submission%5Bimg2%5D=asdf&commit=Create+Submission  

Any idea why adding Foundation broke my form and how to fix it? It's literally the only thing I changed from last night until this morning.

The server log looks like this:

Started GET "/submissions/new" for ::1 at 2016-09-11 13:49:33 +0200  Processing by SubmissionsController#new as HTML    Rendered submissions/_form.html.erb (1.9ms)    Rendered submissions/new.html.erb within layouts/application (2.7ms)  Completed 200 OK in 65ms (Views: 64.8ms | ActiveRecord: 0.0ms)      Started GET "/submissions/new?utf8=%E2%9C%93&authenticity_token=bFFTEWjFXdAojQStCTMLMU2IzNch42jwKWB%2FZPi5G4SGMZxY5TYD9YcoXEgxcoJRrF7piWG56meezS9h%2FdstYg%3D%3D&submission%5Bsubmission_link%5D=asdfas&submission%5Blocation%5D=asdfa&submission%5Bbedrooms%5D=0&submission%5Bbathrooms%5D=0&submission%5Bimg1%5D=asd&submission%5Bimg2%5D=as&submission%5Bimg2%5D=ads&commit=Create+Submission" for ::1 at 2016-09-11 13:49:53 +0200  Processing by SubmissionsController#new as HTML    Parameters: {"utf8"=>"���", "authenticity_token"=>"bFFTEWjFXdAojQStCTMLMU2IzNch42jwKWB/ZPi5G4SGMZxY5TYD9YcoXEgxcoJRrF7piWG56meezS9h/dstYg==", "submission"=>{"submission_link"=>"asdfas", "location"=>"asdfa", "bedrooms"=>"0", "bathrooms"=>"0", "img1"=>"asd", "img2"=>"ads"}, "commit"=>"Create Submission"}    Rendered submissions/_form.html.erb (3.0ms)    Rendered submissions/new.html.erb within layouts/application (3.9ms)  Completed 200 OK in 67ms (Views: 65.9ms | ActiveRecord: 0.0ms)  

My form code looks like this:

<form>      <%= form_for (@submission) do |submission| %>        <div class="row">        <div class="medium-6 columns">          <label>Listing Link            <%= submission.text_field :submission_link, placeholder: "Add the URL for the listing." %>          </label>        </div>        <div class="medium-6 columns">          <label>Location            <%= submission.text_field :location, placeholder: "City, Country" %>          </label>        </div>      </div>        <div class="row">        <div class="medium-6 columns">          <label>Bedrooms            <%= submission.select :bedrooms, ["0", "1", "2", "3+"]%>          </label>        </div>        <div class="medium-6 columns">          <label>Private Bathrooms            <%= submission.select :bathrooms, ["0", "1", "2", "3+"]%>          </label>        </div>      </div>        <div class="row">        <div class="medium-4 columns">          <label>Image 1            <%= submission.text_field :img1, placeholder: "http://i.imgur.com/bCd9Qwl.png?1" %>          </label>        </div>        <div class="medium-4 columns">          <label>Image 2            <%= submission.text_field :img2, placeholder: "http://i.imgur.com/bCd9Qwl.png?1" %>          </label>        </div>        <div class="medium-4 columns">          <label>Image 2            <%= submission.text_field :img2, placeholder: "http://i.imgur.com/bCd9Qwl.png?1" %>          </label>        </div>      </div>        <div class="row">        <div class="medium-12 columns">          <%= submission.submit %>        </div>      </div>      <% end %>    </form>  

My controller:

class SubmissionsController < ApplicationController      def index      @submissions = Submission.all    end      def new      @submission = Submission.new    end      def create      @submission = Submission.new(submission_params)      if @submission.save        redirect_to @submission      else        render :new      end    end      private      def submission_params      params.require(:submission).permit(:submission_link, :title, :location, :bedrooms, :bathrooms, :img1, :img2, :img3)    end  end  

Update text of link_to_add text using nested form in activeadmin

Posted: 11 Sep 2016 04:43 AM PDT

I am using nested attributes in active admin. Here is my code:

form do |f|    f.inputs 'Basic information' do      f.input :event_name    end      if f.object.persisted?      f.inputs 'Examples' do        f.has_many :event_resources do |event_resource|          event_resource.input :event_resource_id, as: :select, collection: EventResource.available_packages          if event_resource.object.persisted?            event_resource.input :_destroy, as: :boolean, label: "Destroy this resource"          end        end        f.link_to_add "Add Resource", :event_resources      end    end    f.actions  end  

I want to update the text of the add link. But i am getting error that link_to_add is not defined for active admin view. Can anyone guide me in right direction. Thanks

access let variables in describe block

Posted: 11 Sep 2016 04:35 AM PDT

so i'm trying to write a spec for this method:

class Student  has_many :payments    def payments_by_year      payments.group_by { |payment| payment.payment_date.year }    end  end  

i made my spec look like this:

RSpec.describe Student do    let!(:student) { create :student, first_name: 'Bruce', last_name: 'Wayne' }    let!(:student2) { create :student, first_name: 'Peter', last_name: 'Parker' }    let!(:payment) { create :payment, student: student, payment_date: Date.new(2016,9,1) }    let!(:payment2) { create :payment, student: student, payment_date: Date.new(2016,8,1) }    let!(:payment3) { create :payment, student: student, payment_date: Date.new(2015,7,1) }      describe '#payments_by_year' do      describe 'returns hash of payments with years as keys' do        subject { student.payments_by_year }          it { is_expected.to eq ####SOMETHING SHOULD BE HERE}      end    end  end  

My problem is i dont know what pass to the :eq method, since i cannot access let variables without exception:

`payment` is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). (RSpec::Core::ExampleGroup::WrongScopeError)  

So i cannot hardcode correct results. How can i access these variables in the describe block?

Rails 5, Passing variable to partial with ajax

Posted: 11 Sep 2016 04:16 AM PDT

I'm new at rails and I'm trying to pass a variable through AJAX to a partial.

First I create a new pedido and then I make an Ajax call to bring some info from the DB. With that Info I need to select a field and save it into the new pedido.

Here is the html for the new pedido page:

#new.html.erb  <%= form_for @pedido do |f| %>      <div id="Cliente">          <%= render 'cliente', f: f %>      </div>  <% end %>  

Now in the pedido controller I have:

#pedido_controller.rb  def new     @pedido = Pedido.new  end    def get_cliente   @cliente = User.find(params[:cliente_id])   respond_to do |format|    format.js { render 'get_cliente', layout: false}   end  end  

I make the Ajax call:

#pedidos.coffee  jQuery ->      $(document).ready ->          $("#pedido_id").on "change", ->              $.ajax                  url: "/pedidos/get_cliente"                  type: "GET"                  data:                      cliente_id: $('#pedido_id option:selected').val()  

My JS file:

#get_cliente.js.erb  $('#Cliente').html( "<%=j render('cliente', :locals => {:cliente =>     @cliente, :f => f }) %>" );  $('#Cliente').slideDown(350);  

And finally my partial has this line:

#cliente.html.erb  <%= f.collection_select(:id, @cliente.user_sucursals.all, :id, :nombre,  {include_blank: true}, {:class => "form-control"}) %>  

So I'd like to save the id from my f.collection_select in _clientes to my new @pedido variable, but I don't know how to assign @pedido variable to my f local in _cliente.

If I take out the line in cliente.html.erb everything works, but I need to add that info to my model.

Thanks in advance!!

Seeding not passing validation

Posted: 11 Sep 2016 05:46 AM PDT

I have churches but churches have a foreign table schedules when they are opened.

churches_list.each do |name, street, city, zip, country, description|    church = Church.new(name: name,                street: street,                 city: city,                 zip: zip,                 country: country,                 description: description)      Schedule.create!(start_date: Date.today+7,                      start_hour: t,                      end_hour: t+8,                      church_id: church.id,                      schedule_type: "oneDay")    church.save  

But when I run the seeds it just states: "church requires at least one schedule"

So I think my church.schedules are not attaching correctly for some reason.

How to write the xls to /tmp and not render it

Posted: 11 Sep 2016 03:56 AM PDT

Currently, I can render .xls in the browser. Unfortunately, this is not a very good idea if the report is big and it takes time to generate the excel file. I'd like to create the excel file in the server, save it first in the /tmp folder then email it to the user. How can I do that?

I can render the excel file like this. I have some code in the corresponding view. I did not use a gem. I just followed the tutorial in Railscasts.

def my_method    @posts = Post.all    #some code    respond_to do |format|      format.xls    end  end  

If the code block below is the way to go. What do I have to do so that it will not render in the browser but get written in the server using the f.write.

path = "/some/file/path.xls"  content = "data to be written"  File.open(path, "w+") do |f|    f.write(content)  end  

I'm on Rails 3.2

Rails 4: Change Database Values

Posted: 11 Sep 2016 05:10 AM PDT

I'm fairly new to rails and struggling on changing database values after the user successfully paid via stripe. Additionally after paying, it somehow redirects me everytime to '/subscriberjobs/1' which doesn't exist. Instead it should direct to the root_path of the application.

Here is what I've got:

Routes

resources :subscriberjobs  resources :jobs  

Jobs Controller

def new    if current_user      @job = current_user.jobs.build    else      redirect_to new_user_session_path    end  end  def create    @job = current_user.jobs.build(job_params)      if @job.save      redirect_to '/subscriberjobs/new'    else      render 'new'    end  end  

Subscriberjobs Controller (Here is what doesn't work!)

class SubscriberjobsController < ApplicationController        before_filter :authenticate_user!        def new      end        def update            token = params[stripeToken]            customer = Stripe::Customer.create(              card: token,              plan: 1004,              email: current_user.email              )            Job.is_active = true # doesn't work          Job.is_featured = false # doesn't work          Job.stripe_id = customer.id # doesn't work          Job.save # doesn't work            redirect_to root_path # doesn't work        end  end  

Please tell me if you need additional information. Every answer is very appreciated. Thanks!

Uploading image to Ruby on Rails breaks up in the middle of the process

Posted: 11 Sep 2016 06:14 AM PDT

Rails version 5.0.0.1 Ruby version 2.2.4

I want to upload an image from android app shot by it's camera to a Ruby on Rails server. During the upload-process I see a lot green of letters, it takes about 50 seconds. Suddenly appears an error. I can only see the end of the error message, because in the error message are the uploaded letters from before printed. Here is the last part of the error:

app/controllers/documents_controller.rb:30:in `block in create'  app/controllers/documents_controller.rb:29:in `create'    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/lay  out    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (31.2ms)    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (0.0ms)    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.0ms)    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layo  ut (1016.0ms)  

Also I receive on my android app error server response code: 500. I sit on this problem for hours. Has somebody an idea what went wrong and how to fix it?

Here is my parameter sent from android app to ruby server:

 Parameters: {"file"=>#<ActionDispatch::Http::UploadedFile:0x53c1b10 @tempfile=#<Tempfile:C:/Users/Clemens/AppData/Local/Temp/RackMultipart20160911-9268-qqwltt.jpg>, @original_  filename="IMG_20160911_122254.jpg", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"document\"; filename=\"IMG_20160911_122254.jpg\"\r\nCo  ntent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n">}  

This is my documents_controller.rb

class DocumentsController < ApplicationController    before_action :set_document, only: [:show, :edit, :update, :destroy]   skip_before_filter :verify_authenticity_token      # GET /documents    # GET /documents.json    def index      @documents = Document.all    end      # GET /documents/1    # GET /documents/1.json    def show      send_data(@document.file_contents,                type: @document.content_type,                filename: @document.filename)    end      # GET /documents/new    def new      @document = Document.new    end       #POST /documents    #POST /documents.json    def create      @document = Document.new(document_params)        respond_to do |format|        if @document.save          format.html { redirect_to documents_path, notice: 'Document was successfully created.' }          format.json { render action: 'show', status: :created, location: @document }        else          format.html { render action: 'new' }          format.json { render json: @document.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /documents/1    # PATCH/PUT /documents/1.json    def update      respond_to do |format|        if @document.update(document_params)          format.html { redirect_to @document, notice: 'Document was successfully updated.' }          format.json { head :no_content }        else          format.html { render action: 'edit' }          format.json { render json: @document.errors, status: :unprocessable_entity }        end      end    end      # DELETE /documents/1    # DELETE /documents/1.json    def destroy      @document.destroy      respond_to do |format|        format.html { redirect_to documents_url }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_document        @document = Document.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def document_params        params.permit(:file)      end    end  

application_controller.rb

class ApplicationController < ActionController::Base    # Prevent CSRF attacks by raising an exception.    # For APIs, you may want to use :null_session instead.   ############ protect_from_forgery with: :exception    protect_from_forgery with: :null_session        end  

models/document.rb

class Document < ActiveRecord::Base      validate :file_size_under_one_mb      def initialize(params = {})      @file = params.delete(:file)      super      if @file        self.filename = sanitize_filename(@file.original_filename)        self.content_type = @file.content_type        self.file_contents = @file.read      end    end      private        def sanitize_filename(filename)        # Get only the filename, not the whole path (for IE)        # Thanks to this article I just found for the tip: http://mattberther.com/2007/10/19/uploading-files-to-a-database-using-rails        return File.basename(filename)      end        NUM_BYTES_IN_MEGABYTE = 1048576      def file_size_under_one_mb       if (@file.size.to_f / NUM_BYTES_IN_MEGABYTE) > 1          errors.add(:file, 'File size cannot be over one megabyte.')        end      end    end  

Error bundle install sqlite3 on Mac OS 10.11

Posted: 11 Sep 2016 06:00 AM PDT

I have the following error while try to install sqlite3 gem using bundler,

Installing sqlite3 1.3.8 with native extensions    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        current directory: /Users/li-xinyang/Desktop/FS_RailsSampleApp/vendor/cache/ruby/2.3.0/gems/sqlite3-1.3.8/ext/sqlite3  /usr/local/opt/ruby/bin/ruby -r ./siteconf20160911-50928-1ikcevl.rb extconf.rb  checking for sqlite3.h... yes  checking for sqlite3_libversion_number() in -lsqlite3... yes  checking for rb_proc_arity()... yes  checking for sqlite3_initialize()... yes  checking for sqlite3_backup_init()... yes  checking for sqlite3_column_database_name()... no  checking for sqlite3_enable_load_extension()... no  checking for sqlite3_load_extension()... no  checking for sqlite3_open_v2()... yes  checking for sqlite3_prepare_v2()... yes  checking for sqlite3_int64 in sqlite3.h... yes  checking for sqlite3_uint64 in sqlite3.h... yes  creating Makefile    To see why this extension failed to compile, please check the mkmf.log which can be found here:      /Users/li-xinyang/Desktop/FS_RailsSampleApp/vendor/cache/ruby/2.3.0/extensions/x86_64-darwin-15/2.3.0/sqlite3-1.3.8/mkmf.log    current directory: /Users/li-xinyang/Desktop/FS_RailsSampleApp/vendor/cache/ruby/2.3.0/gems/sqlite3-1.3.8/ext/sqlite3  make "DESTDIR=" clean    current directory: /Users/li-xinyang/Desktop/FS_RailsSampleApp/vendor/cache/ruby/2.3.0/gems/sqlite3-1.3.8/ext/sqlite3  make "DESTDIR="  compiling backup.c  compiling database.c  compiling exception.c  compiling sqlite3.c  compiling statement.c  statement.c:261:11: warning: implicit declaration of function 'RBIGNUM' is invalid in C99 [-Wimplicit-function-declaration]        if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {            ^  ./sqlite3_ruby.h:16:24: note: expanded from macro 'RBIGNUM_LEN'  #define RBIGNUM_LEN(x) RBIGNUM(x)->len                         ^  statement.c:261:11: error: member reference type 'int' is not a pointer        if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {            ^~~~~~~~~~~~~~~~~~  ./sqlite3_ruby.h:16:36: note: expanded from macro 'RBIGNUM_LEN'  #define RBIGNUM_LEN(x) RBIGNUM(x)->len                         ~~~~~~~~~~  ^  statement.c:261:32: error: use of undeclared identifier 'SIZEOF_BDIGITS'        if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {                                 ^  1 warning and 2 errors generated.  make: *** [statement.o] Error 1    make failed, exit code 2    Gem files will remain installed in /Users/li-xinyang/Desktop/FS_RailsSampleApp/vendor/cache/ruby/2.3.0/gems/sqlite3-1.3.8 for inspection.  Results logged to /Users/li-xinyang/Desktop/FS_RailsSampleApp/vendor/cache/ruby/2.3.0/extensions/x86_64-darwin-15/2.3.0/sqlite3-1.3.8/gem_make.out  

I do have sqlite3 install via Home Brew, and which sqlite3 shows /usr/bin/sqlite3.

The snippet below is the output in mkmf.log file,

 8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: extern void sqlite3_initialize();  14: int t(void) { sqlite3_initialize(); return 0; }  /* end */    --------------------    have_func: checking for sqlite3_backup_init()... -------------------- yes    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  conftest.c:13:57: error: use of undeclared identifier 'sqlite3_backup_init'  int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_backup_init; return !p; }                                                          ^  1 error generated.  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_backup_init; return !p; }  /* end */    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: extern void sqlite3_backup_init();  14: int t(void) { sqlite3_backup_init(); return 0; }  /* end */    --------------------    have_func: checking for sqlite3_column_database_name()... -------------------- no    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  conftest.c:13:57: error: use of undeclared identifier 'sqlite3_column_database_name'  int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_column_database_name; return !p; }                                                          ^  1 error generated.  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_column_database_name; return !p; }  /* end */    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  Undefined symbols for architecture x86_64:    "_sqlite3_column_database_name", referenced from:        _t in conftest-cb897c.o  ld: symbol(s) not found for architecture x86_64  clang: error: linker command failed with exit code 1 (use -v to see invocation)  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: extern void sqlite3_column_database_name();  14: int t(void) { sqlite3_column_database_name(); return 0; }  /* end */    --------------------    have_func: checking for sqlite3_enable_load_extension()... -------------------- no    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  conftest.c:13:57: error: use of undeclared identifier 'sqlite3_enable_load_extension'  int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_enable_load_extension; return !p; }                                                          ^  1 error generated.  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_enable_load_extension; return !p; }  /* end */    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  Undefined symbols for architecture x86_64:    "_sqlite3_enable_load_extension", referenced from:        _t in conftest-be2319.o  ld: symbol(s) not found for architecture x86_64  clang: error: linker command failed with exit code 1 (use -v to see invocation)  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: extern void sqlite3_enable_load_extension();  14: int t(void) { sqlite3_enable_load_extension(); return 0; }  /* end */    --------------------    have_func: checking for sqlite3_load_extension()... -------------------- no    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  conftest.c:13:57: error: use of undeclared identifier 'sqlite3_load_extension'  int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_load_extension; return !p; }                                                          ^  1 error generated.  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_load_extension; return !p; }  /* end */    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  Undefined symbols for architecture x86_64:    "_sqlite3_load_extension", referenced from:        _t in conftest-324aa9.o  ld: symbol(s) not found for architecture x86_64  clang: error: linker command failed with exit code 1 (use -v to see invocation)  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: extern void sqlite3_load_extension();  14: int t(void) { sqlite3_load_extension(); return 0; }  /* end */    --------------------    have_func: checking for sqlite3_open_v2()... -------------------- yes    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  conftest.c:13:57: error: use of undeclared identifier 'sqlite3_open_v2'  int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_open_v2; return !p; }                                                          ^  1 error generated.  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_open_v2; return !p; }  /* end */    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: extern void sqlite3_open_v2();  14: int t(void) { sqlite3_open_v2(); return 0; }  /* end */    --------------------    have_func: checking for sqlite3_prepare_v2()... -------------------- yes    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  conftest.c:13:57: error: use of undeclared identifier 'sqlite3_prepare_v2'  int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_prepare_v2; return !p; }                                                          ^  1 error generated.  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_prepare_v2; return !p; }  /* end */    "clang -o conftest -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe conftest.c  -L. -L/usr/local/Cellar/ruby/2.3.1/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib    -lsqlite3  -lruby.2.3.0 -lsqlite3  -lpthread -ldl -lobjc "  checked program was:  /* begin */   1: #include "ruby.h"   2:    3: /*top*/   4: extern int t(void);   5: int main(int argc, char **argv)   6: {   7:   if (argc > 1000000) {   8:     printf("%p", &t);   9:   }  10:   11:   return 0;  12: }  13: extern void sqlite3_prepare_v2();  14: int t(void) { sqlite3_prepare_v2(); return 0; }  /* end */    --------------------    have_type: checking for sqlite3_int64 in sqlite3.h... -------------------- yes    "clang -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe   -c conftest.c"  checked program was:  /* begin */  1: #include "ruby.h"  2:   3: #include <sqlite3.h>  4:   5: /*top*/  6: typedef sqlite3_int64 conftest_type;  7: int conftestval[sizeof(conftest_type)?1:-1];  /* end */    --------------------    have_type: checking for sqlite3_uint64 in sqlite3.h... -------------------- yes    "clang -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/x86_64-darwin15 -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/backward -I/usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe   -c conftest.c"  checked program was:  /* begin */  1: #include "ruby.h"  2:   3: #include <sqlite3.h>  4:   5: /*top*/  6: typedef sqlite3_uint64 conftest_type;  7: int conftestval[sizeof(conftest_type)?1:-1];  /* end */    --------------------  

Rails code block in controller for repeated code

Posted: 11 Sep 2016 07:38 AM PDT

In my Rails application I am using the odf-report gem to generate reports. However I have an if condition in my method with the same 110 lines of code in each clause with one or two changes at the end. I am wondering if there is a way to define the 110 lines that are being repeated in a code block and just call that code block in my main method? Below is a sample of the method:

def print_enrolment_form_completed    kid = Kid.find(params[:id])    if kid.not_anaphylactic?      report = ODFReport::Report.new("#{Rails.root}/app/reports/Student_Enrolment_Completed.odt") do |r|       #same 110 lines of code       end    else      report = ODFReport::Report.new("#{Rails.root}/app/reports/Student_Enrolment_Completed.odt") do |r|       #same 110 lines of code       end    end  end  

My goal is to just yield a code block where the comment is listed above and have the 110 lines defined elsewhere in the controller. Any ideas are appreciated!

Run job every 10 minutes with Clockwork

Posted: 11 Sep 2016 02:34 AM PDT

I would like a job to run every 10 minutes in Clockwork, but I want it to run 6 times an hour, at 00, 10, 20, 30, 40, and 50 minutes past.

In the Clockwork readme it says you can use wildcards for hour and minute values:

Wildcards for hour and minute are supported:

every(1.hour, 'reminders.send', :at => '**:30')  every(10.seconds, 'frequent.job', :at => '9:**')  

However when I tried at: '**:*0' it gave me an error.

How can I get objects grouped by start_date and end_date in Ruby on Rails

Posted: 11 Sep 2016 05:01 AM PDT

I'm new to Rails. Thank you so much for checking my question.

What I want to do is to extract the data ordered and grouped by start_date and end_date.

Model:

class CreateUserMedicines < ActiveRecord::Migration  def change    create_table :user_medicines do |t|      t.references :user, index: true, foreign_key: true, null: false      t.references :medicine, index: true, foreign_key: true, null: false      t.date :course_start, null: false      t.date :course_end, null: false    end    add_index :user_medicines, [:user_id, :medicine_id]    end  end  

Expected view as each user is like this.

+---+------------+-------------+------------+  |   | start_date |  end_date   |  Medicines |  +---+------------+-------------+------------+  | 1 | 2016/09/11 | 2016/10/01  |  A, B, C   |  | 2 | 2016/09/11 | 2016/09/18  |  D, E      |  | 3 | 2016/09/19 | 2016/09/26  |  F         |  +---+------------+-------------+------------+  

As each medicine (A, B, C), I want to get medicine name and id to add links.

To do this, How do I write controller and model function?

[edit:] My desired result:

{ [ Sun, 11 Sep 2016, Sun, 17 Sep 2016 ]=> [#<UserMedicine:0x007f82c291722>, #<UserMedicine:0x007f82c291349>]  

Current code and result:

record:  @user.user_medicines.group_by(&:course_start)    result:  { [ Sun, 11 Sep 2016 ]=> [#<UserMedicine:0x007f82c291722>, #<UserMedicine:0x007f82c291349>]   

Any answer will be highly appreciated.

ArgumentError in DocumentsController#show: :type option required

Posted: 11 Sep 2016 01:00 AM PDT

I have uploaded an image from android app to a Ruby on Rails server. However when I want to download the file ( in my app you cannot see the picture just the name of the picture and download/destroy button beside), I get this error message:

ArgumentError (:type option required):

app/controllers/documents_controller.rb:14:in `show'    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (6.0ms)    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.0ms)    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (785.0ms)  

So I think there is no file, but I uploaded an file. How can this happen? How can I solve this problem?

Here is my parameter sent from android app to ruby server:

 Parameters: {"document"=>#<ActionDispatch::Http::UploadedFile:0x53c1b10 @tempfile=#<Tempfile:C:/Users/Clemens/AppData/Local/Temp/RackMultipart20160911-9268-qqwltt.jpg>, @original_  filename="IMG_20160911_122254.jpg", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"document\"; filename=\"IMG_20160911_122254.jpg\"\r\nCo  ntent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n">}  

This is my documents_controller.rb

class DocumentsController < ApplicationController    before_action :set_document, only: [:show, :edit, :update, :destroy]   skip_before_filter :verify_authenticity_token      # GET /documents    # GET /documents.json    def index      @documents = Document.all    end      # GET /documents/1    # GET /documents/1.json    def show      send_data(@document.file_contents,                type: @document.content_type,                filename: @document.filename)    end      # GET /documents/new    def new      @document = Document.new    end       #POST /documents    #POST /documents.json    def create      @document = Document.new(document_params)        respond_to do |format|        if @document.save          format.html { redirect_to documents_path, notice: 'Document was successfully created.' }          format.json { render action: 'show', status: :created, location: @document }        else          format.html { render action: 'new' }          format.json { render json: @document.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /documents/1    # PATCH/PUT /documents/1.json    def update      respond_to do |format|        if @document.update(document_params)          format.html { redirect_to @document, notice: 'Document was successfully updated.' }          format.json { head :no_content }        else          format.html { render action: 'edit' }          format.json { render json: @document.errors, status: :unprocessable_entity }        end      end    end      # DELETE /documents/1    # DELETE /documents/1.json    def destroy      @document.destroy      respond_to do |format|        format.html { redirect_to documents_url }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_document        @document = Document.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def document_params        params.permit(:file)      end    end  

application_controller.rb

class ApplicationController < ActionController::Base    # Prevent CSRF attacks by raising an exception.    # For APIs, you may want to use :null_session instead.   ############ protect_from_forgery with: :exception    protect_from_forgery with: :null_session        end  

models/document.rb

class Document < ActiveRecord::Base      validate :file_size_under_one_mb      def initialize(params = {})      @file = params.delete(:file)      super      if @file        self.filename = sanitize_filename(@file.original_filename)        self.content_type = @file.content_type        self.file_contents = @file.read      end    end      private        def sanitize_filename(filename)        # Get only the filename, not the whole path (for IE)        # Thanks to this article I just found for the tip: http://mattberther.com/2007/10/19/uploading-files-to-a-database-using-rails        return File.basename(filename)      end        NUM_BYTES_IN_MEGABYTE = 1048576      def file_size_under_one_mb       if (@file.size.to_f / NUM_BYTES_IN_MEGABYTE) > 1          errors.add(:file, 'File size cannot be over one megabyte.')        end      end    end  

Has anyone an idea how to solve this problem?

Rails permit method not found

Posted: 11 Sep 2016 06:45 AM PDT

I created a new rails app and ran rails g scaffold for 2 different model names (Commit and Repo) with the same exact parameters otherwise. Both views load just fine, but when I try to create a new instance for one of them (Commit) I get an error for permit method not found, but the other one (Repo) works as expected. Can this be name dependant?

class CommitsController < ApplicationController    before_action :set_commit, only: [:show, :edit, :update, :destroy]      # GET /commits    # GET /commits.json    def index      @commits = Commit.all    end      # GET /commits/1    # GET /commits/1.json    def show    end      # GET /commits/new    def new      @commit = Commit.new    end      # GET /commits/1/edit    def edit    end      # POST /commits    # POST /commits.json    def create      @commit = Commit.new(commit_params)        respond_to do |format|        if @commit.save          format.html { redirect_to @commit, notice: 'Commit was successfully created.' }          format.json { render :show, status: :created, location: @commit }        else          format.html { render :new }          format.json { render json: @commit.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /commits/1    # PATCH/PUT /commits/1.json    def update      respond_to do |format|        if @commit.update(commit_params)          format.html { redirect_to @commit, notice: 'Commit was successfully updated.' }          format.json { render :show, status: :ok, location: @commit }        else          format.html { render :edit }          format.json { render json: @commit.errors, status: :unprocessable_entity }        end      end    end      # DELETE /commits/1    # DELETE /commits/1.json    def destroy      @commit.destroy      respond_to do |format|        format.html { redirect_to commits_url, notice: 'Commit was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_commit        @commit = Commit.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def commit_params        params.require(:commit).permit(:sha1, :message)      end  end  

NoMethodError in CommitsController#create undefined method `permit' for "Create Commit":String

Extracted source (around line #72):

# Never trust parameters from the scary internet, only allow the white list through.  def commit_params    params.require(:commit).permit(:sha1, :message)  end  

app\views\commits\index.html.erb

<p id="notice"><%= notice %></p>    <h1>Commits</h1>    <table>    <thead>      <tr>        <th>Sha1</th>        <th>Message</th>        <th colspan="3"></th>      </tr>    </thead>      <tbody>      <% @commits.each do |commit| %>        <tr>          <td><%= commit.sha1 %></td>          <td><%= commit.message %></td>          <td><%= link_to 'Show', commit %></td>          <td><%= link_to 'Edit', edit_commit_path(commit) %></td>          <td><%= link_to 'Destroy', commit, method: :delete, data: { confirm: 'Are you sure?' } %></td>        </tr>      <% end %>    </tbody>  </table>    <br>    <%= link_to 'New Commit', new_commit_path %>  

Rails custom model method in where query

Posted: 10 Sep 2016 10:41 PM PDT

In my rails app I have defined in the Kid model a calculation based on the fields from the Kids DB. the method is as follows:

def flip_date     self.dob.advance(months: 10)   end  

I want to use this in my controller as I have a method where I am defining something as follows:

new_kids = Kid.where(discharge_date: nil).where('flip_date > ?', Date.current.advance(year: 1).beginning_of_year)  

However I keep getting the following error:

SQLite3::SQLException: no such column: flip_date: SELECT "kids".* FROM "kids" WHERE "kids"."discharge_date" IS NULL AND (flip_date < '2017-01-01')  

Any ideas on how can I make this work? All help is appreciated!

How to handle missing dependencies of belongs_to relationship?

Posted: 10 Sep 2016 09:58 PM PDT

I have 4 models User, Flavor, IceCream and Order

User.rb

class User < ActiveRecord::Base    has_many :orders    ...  end  

flavor.rb

class Flavor < ActiveRecord::Base    has_and_belongs_to_many :ice_creams    ...  end  

IceCream.rb

class IceCream < ActiveRecord::Base    has_and_belongs_to_many :flavors    ...  end  

Order.rb

class Order < ActiveRecord::Base    belongs_to :user    has_many :ice_creams    ..  end  

Lets assume that I need to -as an admin- to delete a User that had previously created several orders without deleting those orders from the database. Then when I try to Index orders I come up with an error as the user_id is missing

NoMethodError in Orders#index

undefined method `first_name' for nil:NilClass  <td><%= order.user.first_name + " " + order.user.last_name %></td>  

And this thing of course would happens if I deleted a Flavor that already have been used to create an IceCream.

Any way I found a temporary solution to avoid the error messages that would put a question mark in case the user is missing

<td><%= order.user.present? ? order.user.first_name + " " + order.user.last_name : "?" %></td>  

But actually I don't believe that's the best way to handle such a situation. Also I need to know an Order created by whom even it's former user -employee- And which flavors that order contained even we don't deal with it right now.

I've thought of adding a string column that contain the User name in the Orders table but then I felt it would be over bloating the database.

Also I thought of soft deleting all records Or suspend users not actually delete their records from the data base. But still don't think this is a good Idea.

So I need to know what is the best solution to this situation?

Json uploading image to RoR-Server: NoMethodError undefined method `permit'

Posted: 11 Sep 2016 12:49 AM PDT

I want to upload an image from android app to a Ruby on Rails server but I got an error, that says NoMethodError undefined method `permit'. I think there is something wrong with my parameters. RoR receive these Parameters:

  Parameters: {"document"=>#<ActionDispatch::Http::UploadedFile:0x53c1b10 @tempfile=#<Tempfile:C:/Users/Clemens/AppData/Local/Temp/RackMultipart20160911-9268-qqwltt.jpg>, @original_  filename="IMG_20160911_122254.jpg", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"document\"; filename=\"IMG_20160911_122254.jpg\"\r\nCo  ntent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n">}  

This is my documents_controller.rb

class DocumentsController < ApplicationController    before_action :set_document, only: [:show, :edit, :update, :destroy]   skip_before_filter :verify_authenticity_token      # GET /documents    # GET /documents.json    def index      @documents = Document.all    end      # GET /documents/1    # GET /documents/1.json    def show      send_data(@document.file_contents,                type: @document.content_type,                filename: @document.filename)    end      # GET /documents/new    def new      @document = Document.new    end       #POST /documents    #POST /documents.json    def create      @document = Document.new(document_params)        respond_to do |format|        if @document.save          format.html { redirect_to documents_path, notice: 'Document was successfully created.' }          format.json { render action: 'show', status: :created, location: @document }        else          format.html { render action: 'new' }          format.json { render json: @document.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /documents/1    # PATCH/PUT /documents/1.json    def update      respond_to do |format|        if @document.update(document_params)          format.html { redirect_to @document, notice: 'Document was successfully updated.' }          format.json { head :no_content }        else          format.html { render action: 'edit' }          format.json { render json: @document.errors, status: :unprocessable_entity }        end      end    end      # DELETE /documents/1    # DELETE /documents/1.json    def destroy      @document.destroy      respond_to do |format|        format.html { redirect_to documents_url }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_document        @document = Document.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def document_params        params.require(:document).permit(:file)      end    end  

application_controller.rb

class ApplicationController < ActionController::Base    # Prevent CSRF attacks by raising an exception.    # For APIs, you may want to use :null_session instead.   ############ protect_from_forgery with: :exception    protect_from_forgery with: :null_session        end  

models/document.rb

class Document < ActiveRecord::Base      validate :file_size_under_one_mb      def initialize(params = {})      @file = params.delete(:file)      super      if @file        self.filename = sanitize_filename(@file.original_filename)        self.content_type = @file.content_type        self.file_contents = @file.read      end    end      private        def sanitize_filename(filename)        # Get only the filename, not the whole path (for IE)        # Thanks to this article I just found for the tip: http://mattberther.com/2007/10/19/uploading-files-to-a-database-using-rails        return File.basename(filename)      end        NUM_BYTES_IN_MEGABYTE = 1048576      def file_size_under_one_mb       if (@file.size.to_f / NUM_BYTES_IN_MEGABYTE) > 1          errors.add(:file, 'File size cannot be over one megabyte.')        end      end    end  

When I try to upload the image, I get this error message:

NoMethodError (undefined method `permit' for #<ActionDispatch::Http::UploadedFile:0x59553c0>):    app/controllers/documents_controller.rb:72:in `document_params'  app/controllers/documents_controller.rb:27:in `create'    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (5.0ms)    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.0ms)    Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)    Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (840.0  ms)  

I was long time thinking about this problem. How can I solve this problem? My suggestion is, that Json delivers a String but my ruby on rails program requires a hash. What can I do?

No comments:

Post a Comment