Optional type in Ruby / Rails similar to Swift Posted: 17 May 2016 06:56 AM PDT I know that there is nothing in Ruby that is similar to the Optional type in swift, however in Rails there is try where you can pass the method and its arguments as symbols, isn't that the equivalent to an Optional type, if not what would an Optional type in Ruby look like? |
Rescue MalformedCsvError: Illegal quoting in line n Posted: 17 May 2016 06:40 AM PDT Seems a common issue to have a buggy CSV file when attempting to parse to an array, AR model import, etc. I haven't found a working solution other than open in MS Excel and save as every day (not good enough!). In a 60,000 row externally-provided, daily-updated csv file, there's an error: CSV::MalformedCSVError: Illegal quoting in line 95. (as an example). I'm happy to skip/forget the malformed row (i.e. it has only 1/60000th importance). First attempt is to use CSV.foreach or similar, and simply begin rescue next end to skip the error. No dice. This SO Q&A (How can I further process the line of data that causes the Ruby FasterCSV library to throw a MalformedCSVError?) seems to have promise, but the accepted answer does not...quite...work in my seemingly similar case (modified for example clarity), executed via rake task: file_path = "filename.csv" my_array = [] File.open(file_path).each do |line| # `foreach` instead of `open..each` does the same begin CSV.parse(line) do |row| my_array << row end rescue CSV::MalformedCSVError => er puts er.message counter += 1 next end counter += 1 puts "#{counter} read success" end Output => 1 read success 2 read success ... 94 read success Illegal quoting in line 1 # strange that it says `line 1` vs `95`, which may be the crux of what I do not understand here (e.g. some kind of look ahead error) 96 read success ... 60000 read success # I checked using `line.inspect`, and the 60000th row is indeed being read/inspected rake aborted! CSV:MalformedCSVError: Illegal quoting in line 95 |
My index view doesnt exist on rake routes Posted: 17 May 2016 06:37 AM PDT I understand sorta why my reviser index page isn't showing up, but I don't know how to go about it. In my rake routes there is no reviser#index even though I made a def index on my controller. I have a has_one relation between a user and reviser , as a user can apply to become a reviser . This is the url to show a specific reviser http://localhost:3000/users/15/reviser however I also want there to be a way to see your profile as if you are the current user. That's why I set up an index. So I want a url that shows only my current user as a reviser based off my index ex. http://localhost:3000/users/reviser or http://localhost:3000/reviser how might I be able to make my index page show up as current user page. To sum it up: my ReviserController index isn't showing up in routes. Want url to be http://localhost:3000/reviser for current_user . Thank you! ReviserController: class RevisersController < ApplicationController before_action :set_reviser, only: [:show, :edit, :update] before_action :authenticate_user!, except: [:show] def index @reviser = current_user.reviser end def show end def new @reviser = current_user.build_reviser(params[:reviser]) @user = User.find(params[:user_id]) end def create @reviser = current_user.reviser.build(reviser_params) if @reviser.save redirect_to @reviser,notice: "saved...." else render :new end end def edit set_reviser end def update set_reviser if @reviser.update(reviser_params) redirect_to @reviser,notice: "updated.." else render :edit end end private def set_reviser @reviser = current_user.reviser end def reviser_params params.require(:reviser).permit(:description, :average_start, :average_end, :max_pages, :price_per, :active) end end index.html <div class="row"> <div class="col-md-3"> <ul class="sidebar-list"> <li class="sidebar-item"><%= link_to "Your Reviser Profile", reviser_path, class: "sidebar-list active" %></li> <li class="sidebar-item"><%= link_to "Your Essays", reviser_path, class: "sidebar-list active" %></li> </ul> </div> <div class="col-md-9"> <div class="panel panel-default"> <div class="panel-heading"> Reviser </div> <div class="panel-body"> <% @reviser.each do |reviser| %> <div class="row"> <div class="col-md-2"> <%= link_to image_tag(current_user.avatar.url(:medium), class:'img-responsive'), user_path(user) %> </div> </div> <% end %> </div> </div> </div> </div> routes.rb: resources :users, only: [:index, :show] do resource :reviser end Rake routes: (index for reviser doesn't show up!!!) - user_reviser POST /users/:user_id/reviser(.:format) revisers#create
- new_user_reviser GET /users/:user_id/reviser/new(.:format) revisers#new
- edit_user_reviser GET /users/:user_id/reviser/edit(.:format) revisers#edit
- GET /users/:user_id/reviser(.:format) revisers#show
- PATCH /users/:user_id/reviser(.:format) revisers#update
- PUT /users/:user_id/reviser(.:format) revisers#update
- DELETE /users/:user_id/reviser(.:format) revisers#destroy
- users GET /users(.:format) users#index
- user GET /users/:id(.:format) users#show
|
rails .js.erb views does not work on production server since it work on development machine Posted: 17 May 2016 06:40 AM PDT I don't have any idea why code works on development machine, but doesn't work on production server. I am trying to create live chat between operator and user. In development machine the user's interface and operator's works fluently. I am using pusher as web-sockets. Actually every js.erb view does not work at all in production server. There is some parts of my view. _show.html.erb: <%= content_tag :div, id: "chat-heading", class: %w(mpreview migedit r).include?(action_name) ? 'panel-heading2' : 'panel-heading', style: "font-size:14px;" do %> <%= t :chat_heading %> <i class="fa fa-arrow-up" aria-hidden="true" style="float: right;"></i> <% end %> <div class="panel panel-primary" style="display: none" id="chat-primary" tabindex="0"> <%= content_tag :div, class: 'panel-body', id: 'messages', data: {url: "/#{params[:locale]}/chats/#{@chat.id}/messages/"} do %> <% unless @messages.total_pages < 2 %> <div class="row" id="show-more-aligment"> <div class="col-md-4 col-md-offset-5" style="margin-bottom: 20px;"> <%= link_to 'Show more', url_for(:controller => 'home', :action => 'index', :page => 2, :locale => params[:locale]), :remote => true, :id => 'show_more_link' %> </div> </div> <% end %> <ul class="chat" id="chat-ul"> <% @messages.reverse_each do |message| %> <%= render partial: 'messages/message', locals: {message: message} %> <% end %> </ul> </div> <div class="panel panel-footer"> <div class="row"> <%= simple_form_for @chat.messages.build, url: "/#{params[:locale]}/chats/#{@chat.id}/messages/", :user_id => current_user, remote: true, :html => {:autocomplete => "off"} do |f| %> <div class="col-md-10"> <%= f.input :text, required: true, as: :string, :class => 'btn-input form-control input-sm', :placeholder => "Type your message here...", :label => false %> </div> <div class="col-md-2"> <%= f.submit 'Send', :class => 'btn-chat btn btn-warning btn-sm form-control msg-submit' %> </div> <% end %> <% end %> </div> </div> render of _show.html.erb: <% if user_signed_in? %> <%= content_tag :div, class: %w(mpreview migedit r).include?(action_name) ? 'welcome_chat2' : 'welcome_chat' do %> <%= render 'chats/show' %> <% end %> <% end %> controller for create method: def create @message = @chat.messages.new(params[:message]) @message.user = current_user respond_to do |format| if @message.save format.html {redirect_to @chat} format.js { Pusher.trigger("live_chat_#{@chat.id}", 'chat', {message: @message}) } else format.html {render 'new'} format.js end end end create.js.erb: $('#message_text').val(''); index.js.erb(adding new sent message to chat div): if ($('#chat-ul li').length == 0){ $('ul.chat').html("<%= escape_javascript(render partial: 'messages/message', locals: {message: @message}) %>"); } else { $('ul.chat li:last').after("<%= escape_javascript(render partial: 'messages/message', locals: {message: @message}) %>"); } That's it if I didn't miss something. Basically this code should add new message to database and render it on form send. Actually it saves to database but do not append it to the messages div. It gives 500 internal error. And what is most important in development machine the same exact code works like a charm, but in production it does not. This must be something with server or environment config I guess. Maybe someone has some ideas? Thanks in an advance. ERROR IS HERE |
Sequel validations in concerns Posted: 17 May 2016 06:13 AM PDT I have a Sequel model like this: class User < Sequel::Model include Notificatable def validate super validates_presence [:email] end end # concerns/notificatable.rb module Notificatable extend ActiveSupport::Concern included do def validate super validates_presence [:phone] end end end And here I got a problem: Notificatable validate method overrides the same method in the User model. So there is no :name validations. How can I fix it? Thanks! |
How to create an option for a customer to edit billing & shipping address, and credit card forms for Stripe in Rails? Posted: 17 May 2016 06:03 AM PDT So I'm using Devise and Stripe Subscriptions in my Rails app, and what I want now is to create the forms on a page where customers will be able to edit their billing & shipping address as well their credit card details. I couldn't find documentation that is helpful. So any advice or docs on how to achieve this will be great! Thanks. |
Why is Rails.logger nil in test environment? Posted: 17 May 2016 06:23 AM PDT I'm seeing a NoMethodError in my test environment because of the following call to Rails.logger.error : # /lib/square.rb module Square def self.get_total_sales_for_location(location_id, timeout: 5) begin url = "https://connect.squareup.com/v2/locations/#{location_id}/transactions" headers = {Authorization: "Bearer #{ENV['SQUARE_PERSONAL_ACCESS_TOKEN']}"} response = RestClient::Request.execute headers: headers, method: :get, timeout: timeout, url: url if response.code == 200 JSON.parse response.body else fail end rescue => error Rails.logger.error "Square::get_total_sales_for_location - #{error.message}" raise end end end This all works fine from the console, however running my tests results in: NoMethodError: undefined method 'error' for nil:NilClass My temporary workaround is to use :try to prevent the exception, but that's very kludgy. |
Add Facebook authentication to my Ruby on Rails application with pre-existent email/password authentication Posted: 17 May 2016 06:17 AM PDT I implemented email/password authentication in my application without using Devise (or similar). Now I want to add Facebook authentication maintaining also the email/password authentication method. How can I do this? |
How to do bulk update in rails on habtm association Posted: 17 May 2016 06:11 AM PDT I have two models: #user.rb has_and_belongs_to_many :groups #group.rb has_and_belongs_to_many :users I want to associate groups to users such that many users can be associated to many groups . Front end side of the application is sending the user_ids and group_ids to the update method. So in the UsersController , i've found out each user and associated that user with the groups. def update users = User.where(id: [325, 326]) users.each { |user| user.update(group_ids: [1, 2])} end I need to know the standard way of updating the associated records and what is the most efficient way of updating associated records.? |
Redis connection error on Heroku Posted: 17 May 2016 05:47 AM PDT I have a Rails app which uses Resque for background jobs. This works fine locally, but after deploying to Heroku I get a connection error: Redis::CannotConnectError (Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED)): I see it tries to connect to localhost, which is not correct. I'm using the Heroku Redis :: Redis add-in and I have added the redis gem. This is how initializers.redis.rb looks like: $redis = Redis.new(url: ENV["REDIS_URL"]) And this is my Procfile : web: bundle exec puma -C config/puma.rb resque: env TERM_CHILD=1 bundle exec rake resque:work QUEUE=* COUNT=1 In the config vars REDIS_URL is added. What is going wrong here? |
Rails / CSS styling - how to display same elements from a code block inline Posted: 17 May 2016 05:44 AM PDT I'm building an events app on Rails and I'm currently styling the site. I'm not using bootstrap or foundation, only skeleton & normalize grids. I'm trying to get the events displaying across the page but at the moment they're simply stacking up on top of one another. I understand why but I don't know the solution to fix this. Any assistance would be appreciated. Here's my code - Events - index.html.erb <section id="events"> <div class="container"> <div class="row"> <div class="twelve columns"> <% @events.each do |event| %> <%= link_to (image_tag event.image.url), event %> <h2><%= link_to event.title, event %></h2> <h2><%= link_to event.date.strftime('%A, %d %b %Y'), event %></h2> <% end %> </div> </div> </div> It's the code block - Events - which I'm looking to display inline with each other. No matter which CSS code I use nothing happens - the events just stack on top of each other. section#events { float: left; display: inline; margin-top: 20px; margin: 10px; } |
Why do I get "undefined method 'model_name' "? Posted: 17 May 2016 06:52 AM PDT I'm doing a small experiment and trying to extract some logic from controller's action. I have code like this: Controller def create @user = User.new(user_params) if @user.save redirect_to user_url(@user), notice: 'Welcome to MyApp' else render :new end end And try to create something like this: Controller def create user_service.display end private def user_service RenderService.new(self) end Separate Service object require 'forwardable' class RenderService extend Forwardable delegate [:params, :user_url, :redirect_to, :render] => :@obj attr_reader :obj, :user def initialize(obj) @obj = obj @user = User.new(user_params) end def display redirect_to(user_url(user), notice: 'Welcome to MyApp') if user.save render(:new) unless user.save end private def user_params params.require(:user).permit(:name, :email, :password, :confirmation) end end Form for creating new user = simple_form_for(@user, html: { }) do |form| = form.input :name, required: true = form.input :email, required: true = form.input :password, required: true = form.input :confirmation, required: true = form.submit 'Create my account', class: 'btn btn-primary' As you can see all I tried to do is to encapsulate logic into a separate class, but I got an error from ActionView::Template::Error for some reason and the error says undefined method 'model_name' for nil:NilClass . I really don't understand why it does not work. To me it looks like I sent the same message to the same object and it should work just fine, but it doesn't. Second question: why is ActionView involved here? Thank you for any explanation. Oh, by the way, if you know the code responsible for such behavior and where it lives in the Rails repository please point me to it. Thanks in advance. :) |
How to set auto increment a primary key with a huge data in table in postgres? Posted: 17 May 2016 05:36 AM PDT We are using rails4 with postgresql . We have restore database from a dump in postgresql . We have orders table which is shown below. \d orders; Table "public.orders" Column | Type | Modifiers ------------------------------------+-----------------------------+----------------------------------------------------- id | integer | not null default nextval('orders_id_seq'::regclass) store_id | integer | customer_id | integer | number | character varying(255) | order_status_id | integer | product_total | double precision | discount_total | double precision | tax_total | double precision | shipping_total | double precision | total_cost | double precision | created_at | timestamp without time zone | updated_at | timestamp without time zone | We found the sequence is present . But when creating the order the ids are not autoincremented . What should be the cause? |
500 Internal Server Error when accessing http://redmineexample.com/my/page Posted: 17 May 2016 05:30 AM PDT After migration to new server users haves 500 error when accessing /my/page. Error: Started GET "/my/page" for 172.30.60.118 at 2016-05-17 14:03:31 +0200 Processing by MyController#page as HTML Current user: krzysztof.golos (id=14) Rendered issues/_list_simple.html.erb (24.0ms) Rendered my/blocks/_issuesassignedtome.html.erb (109.1ms) Rendered issues/_list_simple.html.erb (27.5ms) Rendered my/blocks/_issuesreportedbyme.html.erb (39.2ms) Rendered my/blocks/_issueswatched.html.erb (7.2ms) Rendered my/page.html.erb within layouts/base (158.8ms) Completed 500 Internal Server Error in 169.6ms ActionView::Template::Error (no implicit conversion of nil into String): 1: <h3> 2: <%= link_to l(:label_watched_issues), 3: issues_path(:set_filter => 1, :watcher_id => 'me', :sort => 'updated_on:desc') %> 4: (<%= Issue.visible.watched_by(user.id).count %>) 5: </h3> 6: 7: <% watched_issues = issueswatched_items %> app/views/my/blocks/_issueswatched.html.erb:4:in `_app_views_my_blocks__issueswatched_html_erb___2499037382860342811_70277487537940' app/views/my/page.html.erb:29:in `block in _app_views_my_page_html_erb___2611345217716520421_70277481863500' app/views/my/page.html.erb:26:in `each' app/views/my/page.html.erb:26:in `_app_views_my_page_html_erb___2611345217716520421_70277481863500' New server: Redmine version 2.6.10.stable, Ruby version 2.3.1-p112 (2016-04-26)[x86_64-linux], Rails version 3.2.22.2 Old server: Redmine version 2.4.0.stable, Ruby version 1.9.3-p448 (2013-06-27) [x86_64-linux], Rails version 3.2.15 Anybody can help? |
migration not rolling back Posted: 17 May 2016 05:49 AM PDT I had run this migration: class AddUniqueToLocationColumnName < ActiveRecord::Migration def change remove_index :locations, :name add_index :locations, :name, unique: true end end And now I am trying to rollback but its showing error: StandardError: An error has occurred, this and all later migrations canceled: remove_index is only reversible if given a :column option. how can I roll back this migration to my previous version? |
Is it possible to put variables into my query? Posted: 17 May 2016 05:52 AM PDT I've got a postgresql query using some ActiveRecord from Ruby On Rails my_table.location = ActiveRecord::Base.connection.execute("UPDATE my_table SET location = ST_SetSRID(ST_MakePoint(my_table.longitude, my_table.latitude), 4326)::geography") I want to put variables into my query like that because I don't want to use the column longitude and latitude from the database but rather some variables containing longitude and latitude values. my_table.location = ActiveRecord::Base.connection.execute("UPDATE my_table SET location = ST_SetSRID(ST_MakePoint((?), (?), 4326)::geography"), longitude, latitude) I can't find a way to make it work but you should understand the idea behind. Does it exist some method to use variables in my query ? |
Store redirect url for later use in rails 4 Posted: 17 May 2016 05:29 AM PDT I am working on rails 4 application and I am consuming / using API of another site say example.com, which uses 3-legged oauth authorization (same as twitter). To achieve this functionality I have used this link and implemented the same. Here is my implementation AuthController class AuthController < ApplicationController before_filter :authenticate_user! before_filter :fetch_request_token, only: [:authorize] def authorize token = @consumer.get_request_token(oauth_callback: 'http://localhost:3000/auth/fetch_access_token') authorize_url = token.authorize_url redirect_to authorize_url end def fetch_access_token acc_token = request_token.get_access_token(oauth_verifier: params[:oauth_verifier]) # remaining logic redirect_to files_jds_path end private def fetch_request_token #logic for fetching request token end end JDsController class JDsController < AuthController before_filter :authorize, only: [:files, :field_info] unless: :check_access_token def files # logic for the files end def field_info # logic for the files end private def check_access_token # logic for checking access_token end end Currently I am checking the access_token present or not before any action, if access_token not present, then I am fetching the access_token using authorize method. If you see the fetch_access_token method from the AuthController (this is my callback url), where I have hard-coded redirect path as files_jds_path . Because of this implementation though before_filter applied to the field_info , after fetching access_token it redirect to the files_jds_path . But I need to make it generalized so that for any action it will redirect to the respective path. Can anyone suggest how can I do this |
Given an array A[] and a number x, check for pair in A[] with sum as x Posted: 17 May 2016 06:29 AM PDT Given an array A[] and a number x, check for pair in A[] with sum as x. can anyone help me out on this one in rails? |
Paperclip and carrierwave - file does not save + other issues Posted: 17 May 2016 04:30 AM PDT I have few issues about rails app I've made: 1. I've tried to use paperclip and carrierwave, but none of them save the file I want to attach to a specified folder. Attachment should be joined to user model: class UsersController < ApplicationController def new @users = User.new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id redirect_to '/' else redirect_to '/signup' end end private def user_params params.require(:user).permit(:first_name, :last_name, :email, :PESEL, :phone, :cv, :password) end end user controller: class UsersController < ApplicationController def new @users = User.new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id redirect_to '/' else redirect_to '/signup' end end private def user_params params.require(:user).permit(:first_name, :last_name, :email, :PESEL, :phone, :cv, :password) end end paperclip: class AddAttachmentCvToUsers < ActiveRecord::Migration def self.up change_table :users do |t| t.attachment :cv end end def self.down remove_attachment :users, :cv end end What is the task - I want to have users 'joined' with the attachment, and then joined with jobapps model - so it will create new job app id, where the empoyee can decide if it is accepted or not. And I have a trouble with attaching a CV file. |
Rails console: Update attributes and save to DB Posted: 17 May 2016 06:54 AM PDT I want to update existing records in the rails console. Order.all.each do |tname| tname.team = User.where(:id => tname.user_id).pluck(:team).shift end Is working but the result is not getting saved to the DB. Both Order.all.each do |tname| tname.team = User.where(:id => tname.user_id).pluck(:team).shift self.update_columns(team: tname.team) end Or Order.all.each do |tname| tname.team = User.where(:id => tname.user_id).pluck(:team).shift self.update_attributes(team: tname.team) end Are not working. (NoMethodError: undefined method `update_attributes' for main:Object) Any Ideas? Thanks in advance! Edit (schema): create_table "users", force: :cascade do |t| t.text "team" end create_table "orders", force: :cascade do |t| t.integer "user_id" t.string "team" end |
Rails console won't run Posted: 17 May 2016 04:21 AM PDT I seem to be having an issue starting the rails console. This is what happens when i do the bundle exec rails console: neda@ubuntu:~/Documents/RailsProjects/vega$ bundle exec rails console /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/values/time_zone.rb:270: warning: circular argument reference - now SECURITY WARNING: No secret option provided to Rack::Session::Cookie. This poses a security threat. It is strongly recommended that you provide a secret to prevent exploits that may be possible from crafted cookies. This will not be supported in future versions of Rack, and future versions will even invalidate your existing user cookies. Called from: /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-3.2.6/lib/action_dispatch/middleware/session/abstract_store.rb:28:in `initialize'. /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `require': cannot load such file -- test/unit/testcase (LoadError) from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `block in require' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:236:in `load_dependency' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `require' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/test_case.rb:1:in `<top (required)>' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `require' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `block in require' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:236:in `load_dependency' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `require' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-3.2.6/lib/rails/console/app.rb:2:in `<top (required)>' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `require' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `block in require' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:236:in `load_dependency' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `require' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-3.2.6/lib/rails/application.rb:299:in `initialize_console' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-3.2.6/lib/rails/application.rb:152:in `load_console' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-3.2.6/lib/rails/commands/console.rb:27:in `start' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-3.2.6/lib/rails/commands/console.rb:8:in `start' from /home/neda/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-3.2.6/lib/rails/commands.rb:41:in `<top (required)>' from script/rails:6:in `require' from script/rails:6:in `<main>' |
Update deeply nested model upon save Posted: 17 May 2016 04:13 AM PDT I'm attempting to update a deeply nested model from a model that is itself nested using cocoon. (Don't worry, I'll clarify) I have three Models: Stock Stockholder and Folder . Stock has_many :stockholders , which are all nested via cocoon in a form_for @stock . Stockholder has_one :folder . Within my stock form, I have a table that lists out stockholders where I can add new ones (to reiterate, via cocoon). To create a Folder for each new Stockholder , I have a before_create filter in my Stockholder model that creates a new Folder for each new Stockholder (see below) before_create :build_default_folder def build_default_folder logger.debug "Inside build_default_folder" build_folder(name: "#{self.holder_index}. #{self.holder_name}", company_id: self.warrant.company.id, parent_id: self.warrant.company.folders.find_by_name("#{self.warrant.security_series} #{self.warrant.security_class} Warrant").id) true end All of that works very well. The problem Is that I would like to add a method that updates the Folder attributes according to any changes in the stockholder information (say they change the name or something). To this end, I've attempted to add the following. before_update :update_default_folder def update_default_folder logger.debug "Inside update_default_folder" self.folder.update_attributes(name: "#{self.holder_index}. #{self.holder_name}", company_id: self.warrant.company.id, parent_id: self.warrant.company.folders.find_by_name("#{self.warrant.security_series} #{self.warrant.security_class} Warrant").id) true end This however doesn't work and (particularly puzzling to me) is that before_update doesn't even seem to be firing. My best guess would be that this is because stockholder is itself nested using cocoon (but I could be completely wrong about this). Anyway, how might I achieve the desired functionality? Thanks for any suggestions. |
Instagram gem 400: Missing client_secret URL parameter Posted: 17 May 2016 04:13 AM PDT I have been trying to use the Instagram gem for the past few days but couldn't make it work for subsciptions. I am having this error Instagram::BadRequest - POST https://api.instagram.com/v1/subscriptions.json: 400: Missing client_secret URL parameter.: instagram (1.1.6) lib/faraday/raise_http_exception.rb:11:in `block in call' faraday (0.9.2) lib/faraday/response.rb:57:in `on_complete' instagram (1.1.6) lib/faraday/raise_http_exception.rb:8:in `call' faraday_middleware (0.9.2) lib/faraday_middleware/response_middleware.rb:30:in `call' faraday (0.9.2) lib/faraday/response.rb:8:in `call' faraday (0.9.2) lib/faraday/request/url_encoded.rb:15:in `call' instagram (1.1.6) lib/faraday/oauth2.rb:33:in `call' faraday (0.9.2) lib/faraday/rack_builder.rb:139:in `build_response' faraday (0.9.2) lib/faraday/connection.rb:377:in `run_request' faraday (0.9.2) lib/faraday/connection.rb:177:in `post' instagram (1.1.6) lib/instagram/request.rb:31:in `request' instagram (1.1.6) lib/instagram/request.rb:14:in `post' instagram (1.1.6) lib/instagram/client/subscriptions.rb:66:in `create_subscription' app/models/subscription.rb:20:in `process_subscription' app/models/subscription.rb:9:in `create_for' app/controllers/api/v1/applications_controller.rb:42:in `set_subscription' when running this code from my Subscription model. def process_subscription(influencer) token = (User.find(influencer.user_id)).token client = Instagram.client(:access_token => token) client.create_subscription('user', "https://3b582cc1.ngrok.io/subscriptions/process_subscription") end In my controller I handle the callback: def process_subscription if params["hub.challenge"] render :text => params["hub.challenge"] else byebug end I have read some articles like this article but none of them solved my issue. Everything works fine when I do it using curl from my terminal. I am not sure to understand qhy this is not working. |
Undefined method `b64encode' for Base64:Module - Ruby Posted: 17 May 2016 04:56 AM PDT [![enter image description here][1]][1] Hi, I want to encode a string whose length is more than default 60. Therefore, I can't use the Base64.encode64 method. From the following link - http://ruby-doc.org/stdlib-1.8.7/libdoc/base64/rdoc/Base64.html I got to know about b64encode(bin, len = 60) method. But on using, it shows the error - in `<top (required)>': undefined method `b64encode' for Base64:Module (NoMethodError) Where am I making the mistake. PS - The version of Ruby for me is ruby 2.3.0p0 |
Handling duplicate forms in rails Posted: 17 May 2016 05:05 AM PDT I have a website and at times I get duplicate records occuring and looking at the logs It's caused by 2 duplicate forms being submitted within 100-200ms of each other. Is there a way to get rails to reject the second form in such a situation? |
How carrierwave to dynamic field in rails? Posted: 17 May 2016 03:50 AM PDT I'm developing rails app which use MySQL database and ActiveRecord. I have 2 tables - Questions and Answers . Question model has input_type field, which may have photo or text values. Answer model has question_id field and value fields. Problem: value field may contain string or photo inside (it's "dynamic"). How setup carrierwave gem and uploader correctly for this case? (when I setup photo upload for photo -answer - all text answers breaks...) Answer model: class Answer < ActiveRecord::Base belongs_to :question mount_uploader :value, BadgePhotoUploader, mount_on: :value end Uploader: class BadgePhotoUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end def extension_white_list %w(jpg jpeg png) end def content_type_whitelist /image\// end def content_type_blacklist ['application/text', 'application/json'] end end How fix it? Cause it's completely not working, because of problem with different types if value field... |
Custom code to deploy capistrano without gemfile.lock Posted: 17 May 2016 03:45 AM PDT So I made an app in windows and I want to deploy it on an ubuntu server with capistrano. Which doesn't work, because "the gemfile.lock is corrupted" Therefore, I want to do the same thing as Heroku does: delete the gemfile.lock and bundle on the ubuntu server - as I have seen suggested by alot of people. I've read, here for example: Corrupt Gemfile.lock Error with Capistrano, that I should write some custom code that deletes Gemfile.lock before the Bundler task runs (or just remove Gemfile.lock from source control entirely). You'd also have to change the Bundler arguments to remove the --deployment flag, otherwise it will fail when it sees the Gemfile.lock is missing. Can anybody help me with this? I don't understand how to do this... How do I remove Gemfile.lock from source code? Or how do I write this custom code? Where can i find these Bundler arguments? I suppose this is a stupid question, but please help me, I'm really stuck :) |
Show static value in best_in_place rails Posted: 17 May 2016 03:46 AM PDT My code is <%= best_in_place user.user_detail, :unit_number, path: update_unit_number_user_path(user) %> It works fine but I want if unit_number is 0 then it shows "-" . How I do this? |
Ruby on Rails, Highcharts how to render data dynamically for fields instead of columns Posted: 17 May 2016 03:38 AM PDT On the application I am working on I am rendering data from columns in my table - for example: (Model) note.rb def self.getStudentname data = [] self.studentnames.each do |type3| data << self.type3_count(type3) end data end .... private def self.studentnames pluck(:studentname).uniq end def self.type3_count(type3) where(studentname: type3).count end (Controller) notes_controller.rb def dashboard_student @sData = Note.getStudentname() @students = Note.studentnames end (View) dashboard_student.html.erb .... xAxis: { categories: <%=raw @students.to_json %>, title: { text: null }, ..... series: [{ name: 'Number of Notes By Student', data: <%= @sData %> }] As you can see I am getting data from the "studentnames" column in the notes table and rendering on the bar chart in the view which works great. I am looking to get information for fields in columns so, for example, if I have a column named "greivance" and within that a field labeled "late" how would I get information for all the students that are late keeping the rendering dynamic as above? Any guidance much appreciated. Thanks. Can provide more code if needed. |
Cant deploy rails app to heroku Posted: 17 May 2016 03:17 AM PDT I am trying to deploy a simple rails app to heroku but I keep on getting an error no matter what I try to do inorder to fix it. I have tried moving sqlite3 into development and deleting the Gemfile.lock after running bundle but I still get the error. I have tried removing spring and updating gems but I still get the error. At the moment I have no idea of what to do inorder to fix this. This is the log This is the error output when I run git push heroku master. Counting objects: 76, done. Delta compression using up to 8 threads. Compressing objects: 100% (69/69), done. Writing objects: 100% (76/76), 21.53 KiB | 0 bytes/s, done. Total 76 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Ruby app detected remote: -----> Compiling Ruby/Rails remote: -----> Using Ruby version: ruby-2.2.4 remote: ###### WARNING: remote: Removing `Gemfile.lock` because it was generated on Windows. remote: Bundler will do a full resolve so native gems are handled properly. remote: This may result in unexpected gem versions being used in your app. remote: In rare occasions Bundler may not be able to resolve your dependencies at all. remote: https://devcenter.heroku.com/articles/bundler-windows-gemfile remote: remote: -----> Installing dependencies using bundler 1.11.2 remote: Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 remote: Fetching gem metadata from https://rubygems.org/........... remote: Fetching version metadata from https://rubygems.org/... remote: Fetching dependency metadata from https://rubygems.org/.. remote: Resolving dependencies..... remote: Installing json 1.8.3 with native extensions remote: Installing rake 11.1.2 remote: Installing i18n 0.7.0 remote: Installing minitest 5.9.0 remote: Installing thread_safe 0.3.5 remote: Installing builder 3.2.2 remote: Installing erubis 2.7.0 remote: Installing mini_portile2 2.0.0 remote: Installing rack 1.6.4 remote: Installing mime-types-data 3.2016.0221 remote: Installing arel 6.0.3 remote: Using bundler 1.11.2 remote: Installing execjs 2.6.0 remote: Installing coffee-script-source 1.10.0 remote: Installing sass 3.4.22 remote: Installing thor 0.19.1 remote: Installing concurrent-ruby 1.0.2 remote: Installing multi_json 1.12.0 remote: Installing tilt 2.0.4 remote: Installing sqlite3 1.3.11 with native extensions remote: Installing tzinfo 1.2.2 remote: Gem::Ext::BuildError: ERROR: Failed to build gem native extension. remote: /tmp/build_aaf6ac10da8c9ad6f3f235043c390f96/vendor/ruby-2.2.4/bin/ruby -r ./siteconf20160517-323-1j0opc8.rb extconf.rb remote: checking for sqlite3.h... no remote: sqlite3.h is missing. Try 'port install sqlite3 +universal', remote: 'yum install sqlite-devel' or 'apt-get install libsqlite3-dev' remote: and check your shared library search path (the remote: location where your sqlite3 shared library is located). remote: *** extconf.rb failed *** remote: Could not create Makefile due to some reason, probably lack of necessary remote: libraries and/or headers. Check the mkmf.log file for more details. You may remote: need configuration options. remote: Provided configuration options: remote: --with-opt-dir remote: --without-opt-dir remote: --with-opt-include remote: --without-opt-include=${opt-dir}/include remote: --with-opt-lib remote: --without-opt-lib=${opt-dir}/lib remote: --with-make-prog remote: --without-make-prog remote: --srcdir=. remote: --curdir remote: --ruby=/tmp/build_aaf6ac10da8c9ad6f3f235043c390f96/vendor/ruby-2.2.4/bin/$(RUBY_BASE_NAME) remote: --with-sqlite3-dir remote: --without-sqlite3-dir remote: --with-sqlite3-include remote: --without-sqlite3-include=${sqlite3-dir}/include remote: --with-sqlite3-lib remote: --without-sqlite3-lib=${sqlite3-dir}/lib remote: extconf failed, exit code 1 remote: Gem files will remain installed in /tmp/build_aaf6ac10da8c9ad6f3f235043c390f96/vendor/bundle/ruby/2.2.0/gems/sqlite3-1.3.11 for inspection. remote: Results logged to /tmp/build_aaf6ac10da8c9ad6f3f235043c390f96/vendor/bundle/ruby/2.2.0/extensions/x86_64-linux/2.2.0-static/sqlite3-1.3.11/gem_make.out remote: Installing nokogiri 1.6.7.2 with native extensions remote: Installing rdoc 4.2.2 remote: Installing mime-types 3.0 remote: Installing rack-test 0.6.3 remote: Installing autoprefixer-rails 6.3.6.1 remote: Installing uglifier 3.0.0 remote: Installing coffee-script 2.4.1 remote: Installing sprockets 3.6.0 remote: Installing activesupport 4.2.6 remote: An error occurred while installing sqlite3 (1.3.11), and Bundler cannot remote: continue. remote: Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling. remote: Bundler Output: Fetching gem metadata from https://rubygems.org/........... remote: Fetching version metadata from https://rubygems.org/... remote: Fetching dependency metadata from https://rubygems.org/.. remote: Resolving dependencies..... remote: Installing json 1.8.3 with native extensions remote: Installing rake 11.1.2 remote: Installing i18n 0.7.0 remote: Installing minitest 5.9.0 remote: Installing thread_safe 0.3.5 remote: Installing builder 3.2.2 remote: Installing erubis 2.7.0 remote: Installing mini_portile2 2.0.0 remote: Installing rack 1.6.4 remote: Installing mime-types-data 3.2016.0221 remote: Installing arel 6.0.3 remote: Using bundler 1.11.2 remote: Installing execjs 2.6.0 remote: Installing coffee-script-source 1.10.0 remote: Installing sass 3.4.22 remote: Installing thor 0.19.1 remote: Installing concurrent-ruby 1.0.2 remote: Installing multi_json 1.12.0 remote: Installing tilt 2.0.4 remote: Installing sqlite3 1.3.11 with native extensions remote: Installing tzinfo 1.2.2 remote: remote: Gem::Ext::BuildError: ERROR: Failed to build gem native extension. remote: remote: /tmp/build_aaf6ac10da8c9ad6f3f235043c390f96/vendor/ruby-2.2.4/bin/ruby -r ./siteconf20160517-323-1j0opc8.rb extconf.rb remote: checking for sqlite3.h... no remote: sqlite3.h is missing. Try 'port install sqlite3 +universal', remote: 'yum install sqlite-devel' or 'apt-get install libsqlite3-dev' remote: and check your shared library search path (the remote: location where your sqlite3 shared library is located). remote: *** extconf.rb failed *** remote: Could not create Makefile due to some reason, probably lack of necessary remote: libraries and/or headers. Check the mkmf.log file for more details. You may remote: need configuration options. remote: remote: Provided configuration options: remote: --with-opt-dir remote: --without-opt-dir remote: --with-opt-include remote: --without-opt-include=${opt-dir}/include remote: --with-opt-lib remote: --without-opt-lib=${opt-dir}/lib remote: --with-make-prog remote: --without-make-prog remote: --srcdir=. remote: --curdir remote: --ruby=/tmp/build_aaf6ac10da8c9ad6f3f235043c390f96/vendor/ruby-2.2.4/bin/$(RUBY_BASE_NAME) remote: --with-sqlite3-dir remote: --without-sqlite3-dir remote: --with-sqlite3-include remote: --without-sqlite3-include=${sqlite3-dir}/include remote: --with-sqlite3-lib remote: --without-sqlite3-lib=${sqlite3-dir}/lib remote: remote: extconf failed, exit code 1 remote: remote: Gem files will remain installed in /tmp/build_aaf6ac10da8c9ad6f3f235043c390f96/vendor/bundle/ruby/2.2.0/gems/sqlite3-1.3.11 for inspection. remote: Results logged to /tmp/build_aaf6ac10da8c9ad6f3f235043c390f96/vendor/bundle/ruby/2.2.0/extensions/x86_64-linux/2.2.0-static/sqlite3-1.3.11/gem_make.out remote: Installing nokogiri 1.6.7.2 with native extensions remote: Installing rdoc 4.2.2 remote: Installing mime-types 3.0 remote: Installing rack-test 0.6.3 remote: Installing autoprefixer-rails 6.3.6.1 remote: Installing uglifier 3.0.0 remote: Installing coffee-script 2.4.1 remote: Installing sprockets 3.6.0 remote: Installing activesupport 4.2.6 remote: An error occurred while installing sqlite3 (1.3.11), and Bundler cannot remote: continue. remote: Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling. remote: ! remote: ! Failed to install gems via Bundler. remote: ! remote: ! Detected sqlite3 gem which is not supported on Heroku. remote: ! https://devcenter.heroku.com/articles/sqlite3 remote: ! remote: remote: ! Push rejected, failed to compile Ruby app remote: remote: Verifying deploy... remote: remote: ! Push rejected to protected-thicket-11161. remote: To https://git.heroku.com/protected-thicket-11161.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/protected-thicket-11161.git' and this is my Gemfile source 'https://rubygems.org' ruby '2.2.4' gem 'rails', '4.2.6' gem 'sass-rails', '~> 5.0' gem 'bootstrap-sass', '3.2.0.2' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.1.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~> 2.0' gem 'sdoc', '~> 0.4.0', group: :doc gem 'spring', group: :development gem 'puma' gem 'pg' group :development, :test do gem 'byebug' end group :development do gem 'web-console', '~> 2.0' gem 'sqlite3' end gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] I have looked at other questions and none of their solutions have helped me hopefully I can gain some insight on what to do herev on stackoverflow. Thanks |
No comments:
Post a Comment