Affichage des articles dont le libellé est Active questions tagged ruby-on-rails - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged ruby-on-rails - Stack Overflow. Afficher tous les articles

mardi 4 août 2015

Failing to pass arbitrary form parameters to Rails controller

I have a form with several fields that aren't in my model but I'm not able to access them inside my controller.

My new form is fairly simple and was generated with some rails scaffolding. It's inside my controller's create method that I'm not able to access these params.

I've added the params with attr_accessor to my controller, which looks something like:

class LittleClassSessionsController < ApplicationController
  before_action :set_event_session, only: [:show, :edit, :update, :destroy]
  attr_accessor :schedule_type

My view has a form field that looks like this. I can see the parameter's value being submitted in the console.

<select name="schedule_type" id="schedule_type">
  <option value="1">Recurring— Create a series of class sessions in advance</option>
  <option value="2">Not recurring— Create just one class session in advance</option>
</select>

I've added :schedule_type to my whitelisted params. When trying to puts the params to my console, it's not in there.

What am I missing?



via Chebli Mohamed

ActionController::RoutingError (No route matches [GET] "/scan"):

Getting an error for a simple index route in rails:

Here are my routes:

Prefix Verb URI Pattern           Controller#Action
scan_index GET  /scan/index(.:format) scan#index
      root GET  /                     scan#index
      scan GET  /scan(.:format)       scan#index

Yet, typing in the following url:

http://ift.tt/1Ulkpus

Produces the following in error_log:

I, [2015-08-04T15:38:42.902191 #24943]  INFO -- : Started GET "/scan" at 2015-08-04 15:38:42 +0000
F, [2015-08-04T15:38:42.902936 #24943] FATAL -- : 
ActionController::RoutingError (No route matches [GET] "/scan"):



via Chebli Mohamed

Rails - Controller that does not check for CSRF token

In my rails application, one of the controllers displays public statistics that I want websites hosted on different domains to pull data from. (http://ift.tt/1ML3M9n)

My controller code is given below:

class StatsController < ApplicationController 
require 'ostruct'
skip_before_action :verify_authenticity_token
respond_to :html, :xml, :json, :csv

def index
    @stats = OpenStruct.new
    @stats.users = User.all.count
    @stats.organizations = Organization.all.count
    @stats.donors = Person.all.count
    respond_to do |format|
        format.json {render json: @stats}
    end
end
end

I thought the line skip_before_action :verify_authenticity_token would be enough, but when I try to make requests to this page from the console, I get the following error:

XMLHttpRequest cannot load http://ift.tt/1ML3M9n. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

How can I fix this?



via Chebli Mohamed

How do I specify the join table on a has_many through association?

I have a users table (admin_users) a join table (UserCompanies) and a companies table (Companies), each has an active record model (AdminUser, TableModule::UserCompany, TableModule::Company). I want to do something like the following:

AdminUser.first.companies

But, my attempts so far are not working, I'm assuming because I need to specify the table names, model names, or key names, but I don't know how that works with a has_many through relationship. Here is my best attempt at defining it so far:

class AdminUser < ActiveRecord::Base
    has_many :companies, through: :user_company, source: "TableModule::UserCompany"
end

How do I properly specify this relationship?



via Chebli Mohamed

Unable to send mail with attachment using Mandrill-api gem (Rails 4.1)

Emails without attachment are delivered fine, but when there is an attachment I get the following error in production:

ArgumentError: An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.

  • Letter opener in dev model shows the email rendering perfectly
  • This error only shows up in production

the call to mailer is:

# template variables
merge_vars = {"AMOUNT" => "100"}

invoice = Invoice.new(customer)

attachments[invoice.name] = {
  data: invoice.invoice_data,
  mime_type: 'application/pdf'
}

mail(to: user.email, cc: cc_emails.compact.uniq, subject: mail_subject, content_type: content_type) do |format|
  # Template renders fine
  format.html{mandrill_template('invoice_template', merge_vars)}
end

InvoiceMailer < ActionMailer::Base has defaults for "from" and "reply_to"

Mandril gem version 1.0.53 and Rails 4.1.10.



via Chebli Mohamed

How can I call a method within active_scaffold?

I can't seem to find any questions similar to this that have been asked. Maybe this means I am way off and this is a dumb question.

I am trying to add a feature to a preexisting app. This feature allows the user to copy a report over to the next period (a fiscal year).

Here is the abridged active_scaffold code:

active_scaffold :report do |config|
  config.list.columns = [:user, :period, :division, :released, :reportable, :comp_plan]
  config.create.columns = [:user, :period, :division, :released, :reportable, :comp_plan]
  config.update.columns = [:user, :period, :division, :released, :reportable, :comp_plan]

  config.actions.exclude :show

  config.columns[:user].form_ui = :select
  config.columns[:period].form_ui = :select

  config.columns[:user].clear_link
  config.columns[:period].clear_link

  config.columns[:user].search_sql = ["users.first_name", "users.last_name"]
  config.search.columns << :user

  config.nested.add_link :access_rights, :label => 'Access'
end

Now I want to add a link to each row which calls a function which copies that report.

Any ideas are greatly appreciated.

Edit: Most of the code probably isn't relevant to the question but I figure it would be helpful to see anyways.



via Chebli Mohamed

Paperclip S3 Bucket and Rails Images will upload but will not display

I am using paperclip gem along with an AWS s3 bucket to upload images to my app. I have it all working properly and the images will upload to the actual bucket and the web pages will load. The only problem is the images themselves will not display and it will only display their names like enter image description here

to display the image I am using the code

<%= image_tag @post.image.url(:medium), class: "edit_recipe_image" %>

has any one experiences this before or possibly know a solution to fix this?

Thanks in advance!



via Chebli Mohamed

Android post json to API in background

i have two applications, i have the android app and the Ruby on Rails API. In android i have a SQLite database and almost all the time i need sync the android database with the API database, but this synchronization can take a "long time", something like 10 seconds if is the first sync, so user need to keep waiting and looking to load screen until the process done.

So, i want send a post to the Ruby on Rails application, but without "stop" the application in the load screen, i want to do this sync in background, so the user wont realise that the app is syncing with the API.

Now, i'm trying to working with threads, but it still fails.

Thanks.



via Chebli Mohamed

How to use devise_token_auth with Devise, Angular and Mongoid

I'm trying to use Mongoid, devise, devise_token_auth and ng-token-auth for an token based authorisation for an API written in Rails with Mongoid and Angular as the client.

The problem is when I follow the steps to install devise_token_auth I get an error when I restart my Rails app: undefined methodtable_exists?' for User:Class`

I'm assuming that because I'm using Mongoid the User class don't have the table_exists? method.

How can I get around this? Or, more importantly how can I get this to work?

EDIT: Here's my User class

class User

  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Enum

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  ## Database authenticatable
  field :email,              type: String, default: ""
  field :encrypted_password, type: String, default: ""

  ## Recoverable
  field :reset_password_token,   type: String
  field :reset_password_sent_at, type: Time

  ## Rememberable
  field :remember_created_at, type: Time

  ## Trackable
  field :sign_in_count,      type: Integer, default: 0
  field :current_sign_in_at, type: Time
  field :last_sign_in_at,    type: Time
  field :current_sign_in_ip, type: String
  field :last_sign_in_ip,    type: String

  ## Confirmable
  field :confirmation_token,   type: String
  field :confirmed_at,         type: Time
  field :confirmation_sent_at, type: Time
  field :unconfirmed_email,    type: String # Only if using reconfirmable

  include DeviseTokenAuth::Concerns::User

  attr_accessor :reset_token

  enum :role, [:admin, :author]

  after_initialize :set_default_role, :if => :new_record?
  before_create :set_auth_token

  field :first_name,                                        type: String
  field :last_name,                                         type: String
  field :domain,                                                type: String
  field :payment_details,                               type: Hash
  field :subscriber,                                        type: Boolean
  field :stripe_details,                                type: Hash
  field :theme,                                                 type: String

  # Validation
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
    before_save { self.email = email.downcase }
    before_create :create_remember_token


  # Get rid of devise-token_auth issues from activerecord
  def table_exists?
    true
  end

  def columns_hash
    # Just fake it for devise-token-auth; since this model is schema-less, this method is not really useful otherwise
    {} # An empty hash, so tokens_has_json_column_type will return false, which is probably what you want for Monogoid/BSON
  end

  def set_default_role
      self.role ||= :admin
  end

end

EDIT 2: Adding stack trace

http://ift.tt/1P4iXd5



via Chebli Mohamed

Passenger Phusion sub-uri with Apache HTTPD without virtualHost Ruby on Rails 4

Trying to deploy my application to a sub-uri. such as, [IP ADDRESS]/sub-domain instead of just [IP address]. so, the instructions at passenger assume that you have a virtualhost already established in your code (http://ift.tt/1IW0ror). Does anybody know how to get this working with the latest version of Passenger and Rails in the HTTPD config file?



via Chebli Mohamed

attr_accessible error on rails 4.1.8 upon performing rake db:migrate on heroku

I am still learning Ruby (so I am a complete noob), right now I have my app successfully running locally but when trying to opening the apps on heroku , in which I first perform the heroku run rake db:migrate I stumbled upon a problem.. it tells me :

Running `rake db:migrate` attached to terminal... up, run.2149
-- attr_accessible(:pName, :pQuantity, :pMeter, :pWeight, :pSellPrice,  :pCategory, :pPic)
-- attr_accessible(:pName, :pQuantity, :pMeter, :pWeight, :pSellPrice, :pCategory, :pPic)
rake aborted!
NoMethodError: undefined method `attr_accessible' for #<ActiveRecord::Migration:0x007f2dc2ba45b8>
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:648:in `block in method_missing'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:621:in `block in say_with_time'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:621:in `say_with_time'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:641:in `method_missing'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:406:in `method_missing'
/app/db/migrate/20150802134246_create_inventories.rb:2:in `<class:CreateInventories>'
/app/db/migrate/20150802134246_create_inventories.rb:1:in `<top (required)>'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `require'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `block in require'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:232:in `load_dependency'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `require'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:761:in `load_migration'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:757:in `migration'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:752:in `disable_ddl_transaction'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:1044:in `use_transaction?'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:954:in `rescue in block in migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:951:in `block in migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:948:in `each'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:948:in `migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:807:in `up'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:785:in `migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/railties/databases.rake:34:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:migrate

I have been trying to find out the reason, after wondering around I found out about change in rails 4.0.0 in that attr_accessible are no longer used and we should use strong parameter instead, So removing the attr_accessible from model will solve the problem...

However, I have an empty Model, there is no attr_accessible everywhere i look. (beside this is weird why my apps runs locally but not on heroku?) I can't figured out why this error appear and where to look for solutions.. I have been trying to look at active_record file but am afraid of making any changes, any idea?

also, could anyone tell me any resources that can help me read this type of log errors? I have tried to read some articles but can't find one that is easy to understand for noobs like me... ;(



via Chebli Mohamed

Dragonfly images in a polymorphic association syntax?

I have a pictures model:

class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
  dragonfly_accessor :image
end

And then I have two different models that should be able to have pictures:

class Teacher < User 
  has_many :pictures, as: :imageable  
end

class Student < User 
  has_many :pictures, as: :imageable
end

I followed instruction here to setup dragonfly and had it working when I just had one model with an image attribute but now that I want to make its own picture model that other models can have_many of then it stops working: http://ift.tt/1P4iXd3

In my rails console I can do something like:

teacher = Teacher.last
teacher.pictures 

and get returned an empty active record proxy:

#<ActiveRecord::Associations::CollectionProxy []>

but I cannot do:

teacher = Teacher.last
teacher.image
teacher.picture.image
teacher.pictures.image

When I try to display on my show view:

<%= image_tag @teacher.pictures.thumb('400x200#').url if @teacher.pictures_stored? %>

I get

undefined method `pictures_stored?'

Even if I delete the if @scientist.pictures_stored? I then get this error: undefined method thumb'

I have tried different combinations since dragonfly gives us the dragonfly_accessor :image on our pictures model. But not sure how to actually reference it. Any help is appreciated.



via Chebli Mohamed

mongoid-4 how to validate uniqueness of belongs_to in 1 to 1 association

I have a 1-to-1 association between 2 mongoid models and I keep getting duplicates, that is having more than one child record(card) with same parent_id(that is user). I have tried validating uniqueness of the belongs_to association has shown below, but it doesn't work.

 class User
   include Mongoid::Document
   field :name, type: String 
   has_one :card
 end

The second model:

 class Card
   include Mongoid::Document
   field :name, type: String 
   belongs_to :user

   validates :user, :uniqueness => {:scope => :user_has_child}

   def user_has_child
     q = Segment.where(drop_id: {'$ne' =>  nil})
     s = q.map(&:drop_id)
     errors.add(:drop_id, "this user already has a card") if s.include?(:drop_id)
   end

 end



via Chebli Mohamed

Modify Devise SAML Attributes

I'm using Rails 4 and Devise with Devise SAML Authenticatable for my Account system.

I've got the SAML working and all, but am trying to work out one thing.

I'd like to change one of the SAML attributes before saving it (since it is formatted incorrectly). Essentially, the Account's SAML request is given a role attribute which is one of the following Group_admin, Group_consumer, Group_supplier. I have a role field in my Account model enumerated as follows:

enum role: [:admin, :consumer, :supplier]

Clearly I can't directly set role because Group_admin != admin (etc.). Is there a way to modify the SAML attribute that is given before Devise saves the field?

I've tried a before_save filter to no avail.

before_save :fix_role!

private
def fix_role!
  self.role = self.role.split('_')[1]
end

Does anyone know of a way to do this? I can post any other code if necessary, I'm just not sure what else is needed. Thanks.



via Chebli Mohamed

How do I call exposed methods in C# DLL from Ruby on Linux using Mono?

I have a DLL which contains code that I would like to access from Microsoft Visual Foxpro as well as Ruby on Rails.

I set up a C# DLL and generated the corresponding .so file using Mono according to this question. mono --aot -O=all dlltest.so

As noted in that question, the function nm -Ca dlltest.so shows a form of my method, but FFI cannot see it.

Also as mentioned in that question, nm -D --defined-only dlltest.so indicates that my method is not defined. However, FFI can see and access the one that is defined as mono_aot_file_info.

It seems like the poster of that question was close to getting it to work, but I was unable to find anything about why the method is showing as not defined or how to change that.

Is there something I can do to define the methods in the .so file? Or is this not possible?

Note that the method is exposed in the DLL, and FoxPro can access it just fine.



via Chebli Mohamed

Ruby on Rails frontend and Java backend architecture?

I am building a Ruby on Rails webapp and it is great for the web front end, display, what the user sees etc. But I want request from a user that involves some heavy processing to be done inside a Java backend layer.

So my question what do you think is the best approach for joining these two layers up? I can think of two approaches:

  1. Building up the request into a JSON object in the Ruby on Rails layer and using RabbitMQ to send it as a message to the Java backend layer which sends another JSON object back in a message as a response. I tend to lean more towards this approach as there a nice RabbitMQ clients for Ruby and Java.

  2. Have a my Java layer running on a web server(such as Tomcat or maybe Netty?) that accepts HTTP requests from the Ruby on Rails layer and sends the response back through the server using HTTP?

Note any persistence will be handled by the Java layer also.

Any more ideas or and/or comments on the above two ideas would be great.

Thanks.



via Chebli Mohamed

Random order using mongoid on rails 4

I trying to get results in random order, but I can't find anything in the documentation. I want something like order random on postgresql

 .order("RANDOM()")

thanks in advance.



via Chebli Mohamed

"Stripe" gem in rails - how to change redirect upon payment?

The Stripe gem has an inherent redirect to their "Thanks, you paid $x". How can I redirect, instead of to this "create" view, to a different route?

Thank you!



via Chebli Mohamed

Allow users to sort images based on category selected (paperclip gem) - Rails

Currently my home page (index.html.erb) shows all the user images loaded within the past 24 hours, which is part of posts. However I would like to add a form that allows the user to sort images based on their category and upload date. (For example images with the category music, uploaded within the past month) I understand how to query the database but I dont know how to take the user input. When I create a form, suing simple form: <%= simple_form_for @posts do |f| %>, it throws an error, saying I cannot use an object. Ive thought about ajax but it doesnt seem to work well with the paperclip gem, plus I rather get it done on the backend. I hope my issue well enough. If not feel free to comment as I will be around to respond. Thanks in advance.

Post Controller:
 def index  
 @posts = Post.all.where(created_at:(Time.now - 1.day)..Time.now)
 end

Schema for Post table:

create_table "posts", force: :cascade do |t|
t.string   "title"
t.string   "instagram"
t.text     "description"
t.datetime "created_at",                            null: false
t.datetime "updated_at",                            null: false
t.integer  "user_id"
t.string   "image_file_name"
t.string   "image_content_type"
t.integer  "image_file_size"
t.datetime "image_updated_at"



via Chebli Mohamed

RoR: jquery file upload on submit form button

How do I make it so my submit button will upload the images?

<%= simple_form_for @project, html: { multipart: true, id: 'fileupload' } do |f| %>

  <span class="btn btn-success fileinput-button">
    <i class="glyphicon glyphicon-plus"></i>
    <span>Add files...</span>
    <input type="file" name="photos[]" id='photo_upload_btn', multiple>
  </span>
  <button type="submit" class="btn btn-primary start">
    <i class="glyphicon glyphicon-upload"></i>
    <span>Start upload</span>
  </button>
  <button type="reset" class="btn btn-warning cancel">
    <i class="glyphicon glyphicon-ban-circle"></i>
    <span>Cancel upload</span>
  </button>

  <%= f.button :submit, class: "btn btn-primary pull-right" %>
<% end %>


<script>
$(function () {

'use strict'; //not even sure what this is for

$('#fileupload').fileupload({

});
    // Load existing files:
    $('#fileupload').addClass('fileupload-processing');
    $.ajax({
        url: $('#fileupload').fileupload('option', 'url'),
        dataType: 'json',
        context: $('#fileupload')[0]
    }).always(function () {
        $(this).removeClass('fileupload-processing');
    }).done(function (result) {
        $(this).fileupload('option', 'done')
            .call(this, $.Event('done'), {result: result});
    });
});
</script>

Right now, when I upload an image, it'll show thumbnail preview and start button with a cancel button. I want to move the start button and have it all upload using the submit button.



via Chebli Mohamed