Saturday, October 22, 2016

Why put the business logic from controller to the model? [on hold] | Fixed issues

Why put the business logic from controller to the model? [on hold] | Fixed issues


Why put the business logic from controller to the model? [on hold]

Posted: 22 Oct 2016 07:12 AM PDT

For rails development, I was told that it is better to move logic from controller to model, anyone could point me the reason about this?

Ruby on Rails - undefined method `errors' for nil:NilClass

Posted: 22 Oct 2016 05:38 AM PDT

This questions seems duplicate but I have checked all other related questions and none of the answers apply as I have tried them all.

I am trying to create a user signup form.

My user model (user.rb) is like this.

class User < ApplicationRecord    attr_accessor :password    EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i    validates :username, :presence => true, :uniqueness => true, :length => { :in => 4..20 }    validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX    validates :password, :confirmation => true #password_confirmation attr    validates_length_of :password, :in => 6..20, :on => :create  end  

The user controller (users_controller.rb) is like this

class UsersController < ApplicationController      def new      @user = User.new    end      def create        @user = User.new(user_params)        if @user.save          flash[:notice] = "You have signed up successdully"          flash[:color] = "valid"      else          flash[:notice] = "Invalid Input!"          flash[:color] = "invalid"      end    end        def user_params        params.require(:username).permit(:email, :password, :password_confirmation)      end             render "new"    end  

And the users new view (new.html.erb) is like this.

<% @page_title = "UserAuth | Signup" %>  <div class="Sign_Form">    <h1>Sign Up</h1>    <%= form_for(:user, :url => {:controller => 'users', :action => 'create'}) do |f| %>      <p> Username:</br> <%= f.text_field :username%> </p>      <p> Email:</br> <%= f.text_field :email%> </p>      <p> Password:</br> <%= f.password_field :password%></p>      <p> Password Confirmation:</br> <%= f.password_field :password_confirmation%> </p>      <%= f.submit :Signup %>    <% end %>    <% if @user.errors.any? %>      <ul class="Signup_Errors">      <% for message_error in @user.errors.full_messages %>        <li>* <%= message_error %></li>      <% end %>      </ul>    <% end %>  </div>  

The routes (routes.rb) are like this

Rails.application.routes.draw do    get 'users/new'    resources :users      # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html    root 'home#index'  end  

And rake route gives me following output.

   Prefix Verb   URI Pattern               Controller#Action  users_new GET    /users/new(.:format)      users#new      users GET    /users(.:format)          users#index            POST   /users(.:format)          users#create   new_user GET    /users/new(.:format)      users#new  edit_user GET    /users/:id/edit(.:format) users#edit       user GET    /users/:id(.:format)      users#show            PATCH  /users/:id(.:format)      users#update            PUT    /users/:id(.:format)      users#update            DELETE /users/:id(.:format)      users#destroy       root GET    /                         home#index  

Yet when I try to access http://localhost/users/new from my browser, I get the following error.

Showing C:/Sites/expenses/app/views/users/new.html.erb where line #11 raised:    undefined method `errors' for nil:NilClass  Extracted source (around line #11):  9  10  11  12  13  14        <%= f.submit :Signup %>    <% end %>    <% if @user.errors.any? %>      <ul class="Signup_Errors">      <% for message_error in @user.errors.full_messages %>        <li>* <%= message_error %></li>  

Rails mailman, receiving and saving emails with embedded images ?

Posted: 22 Oct 2016 04:50 AM PDT

Is it possible, using mailman gem, to receive and save e-mails with embedded images? Currently I can save body's html_part to Emails table using Email.create! body: message.html_part.body.decoded and this works fine, but it doesn't store embedded images. Is there any way to save body with image? I tried to convert it to binary using message.html_part.body.decoded.to_s(2) but then I get ArgumentError exception. Images are required, because this e-mail will be resent at a later stage and I would like to preserve its original content(with embedded images). Any thoughts? Cheers.

OAuth facebook with rails

Posted: 22 Oct 2016 04:23 AM PDT

I have a rails application, I want to add them to authenticate via Facebook, in its application to authenticate I use devise, I read the documentation to devise and how to add to it Oauth now I have this code

omniauth_callbacks_controller.rb

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController  def facebook    @user = User.from_omniauth(request.env["omniauth.auth"])    if @user.persisted?    byebug    sign_in_and_redirect @user, :event => :authentication    set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?  else    session["devise.facebook_data"] = request.env["omniauth.auth"]    redirect_to new_user_registration_url  end  end  def failure    redirect_to root_path   end  end  

routes.rb

devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }  

devise.rb

Devise.setup do |config|  config.omniauth :facebook, ENV['APP_ID'], ENV['APP_SECRET'],                callback_url: ENV['CALLBACK_URL'],                scope: 'email    user.rb  devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable  devise :omniauthable, :omniauth_providers => [:facebook]    def self.from_omniauth(auth)    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|      user.email = auth.info.email      user.password = Devise.friendly_token[0,20]    end  end    def self.new_with_session(params, session)    super.tap do |user|      if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]        user.email = data["email"] if user.email.blank?      end    end  end  def self.find_for_facebook_oauth(access_token)    if user = User.where(:url => access_token.info.urls.Facebook).first      user    else      User.create!(:provider => access_token.provider, :url => access_token.info.urls.Facebook, :username => access_token.extra.raw_info.name, :nickname => access_token.extra.raw_info.username, :email => access_token.extra.raw_info.email, :password => Devise.friendly_token[0,20])    end  end  

omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do    provider :facebook, ENV['APP_ID'], ENV['APP_SECRET']  end  

and have facebook enter image description here enter image description here

please help me, what am I doing wrong

Rails - CKEditor with Carrierwave

Posted: 22 Oct 2016 04:02 AM PDT

My model with images:

class Post < ApplicationRecord      mount_uploader :image, ImageUploader  end  

My uploader:

class ImageUploader < CarrierWave::Uploader::Base      include CarrierWave::MiniMagick      storage :file      def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end      def extension_whitelist      %w(jpg jpeg gif png)    end    end  

I can add a post with an image inside it. It is displayed properly. I can also delete a post, but what I noticed is that the files from public/uploads/ckeditor/pictures are not removed after removing a post.

Two questions:

  1. How can I fix this?
  2. Is there a better way to create a blog post with pictures other than CKEditor + Carrierwave?

Data not retrieved from Google Drive with the service account (Ruby on Rails)

Posted: 22 Oct 2016 04:01 AM PDT

Hi I created the google service account with the email A@gmail.com. I downloaded secret json file and put into the working directory. Then initialize and authorize api with this type of commands.

scopes = ["https://www.googleapis.com/auth/drive"]  service = Google::Apis::DriveV3::DriveService.new  service.client_options.application_name = APPLICATION_NAME  service.authorization = Google::Auth.get_application_default(scopes)  

It works at this stage with the out of

https://www.googleapis.com/oauth2/v3/token>, @client_id=nil, @client_secret=nil, @code=nil, @expires_at=nil, @expires_in=nil, @issued_at=nil, @issuer="brbr@appspot.gserviceaccount.com", @password=nil, @principal=nil, @redirect_uri=nil, @scope=["https://www.googleapis.com/auth/drive"], @state=nil, @username=nil, @expiry=60, @audience="https://www.googleapis.com/oauth2/v3/token", @signing_key=#, @extension_parameters={}, @additional_parameters={}>

Then, I ran the below command as Google api document explains.

response = service.list_files(page_size: 10,                                fields: 'nextPageToken, files(id, name)')  puts 'Files:'  puts 'No files found' if response.files.empty?  response.files.each do |file|    puts "#{file.name} (#{file.id})"  end  

The only file that is retrieved is "Getting Started" file even if I recalled with page_size 10.

Inside of google drive whose email account is A@gmail.com, I created a couple of files ( google document, google spread sheet , etc) but none of them are retrieved with the command above.

Is that because of the service account?

For instance, my service account email(client_email) is brbrbrbr...@appspot.gserviceaccount.com, which is apparently different from A@gmail.com.

Please give me any idea on this issue!

Best

Rails 5 ActionCable on Heroku uninitialized constant NameError

Posted: 22 Oct 2016 03:49 AM PDT

I'm aware of the fact that Heroku only allows 2 ports, i.e. 80 and 443 for connection, which is why you need to run a separate server for WebSockets. I came across this guide which claims to allow you to run both processes on the same server. I also changed the line:
if Faye::WebSocket.websocket?(env) to:
::WebSocket::Driver.websocket?(env) as per a comment by a user, since I'm not using Faye.
However, I get the error uninitialized constant ChatActionCable (NameError). I tried the guide on this page, yet no gain.

My application.rb file looks like this:

require_relative 'boot'    require 'rails/all'    module Third    class Application < Rails::Application      config.autoload_paths += %W(#{config.root}/lib)    end  end  

TIA.

Ruby on Rails - Devise - Cannot save user with many-to-many associations

Posted: 22 Oct 2016 04:45 AM PDT

I am trying to create a new User with multiple Roles using Ruby on Rails 5.0 and Devise 4.0.

I am using a form and this is what my sign_up_params look like:

{    "role_ids"=>["17", "19", "16", "18"],    "email"=>"john@john.com",    "password"=>"123123",    "password_confirmation"=>"123123"  }  

This is what my controller looks like:

def create    @user = User.new(sign_up_params)    if @user.save      redirect_to :root, notice: 'Well done'    else      render :new    end  end  

The line with if @user.save fails.

@user.errors gives @messages={:user_roles=>["is invalid"]} and I have no idea why.

More info:

More digging and I found out that, indeed, my middle table is invalid because it has a role_id but no user_id because the user hasn't been saved yet. The problem is that I am trying to save everything all at once. Rails should be smart enough to understand that I want to save the user and all the "pending" associations? If not, how can I do? Calling user.save doesn't allow me to save the user.

Hope to have been clear enough as to what the problem is. I think that I am doing the wrong things in the controller but I don't know how to do better.. and ideally I would still wanna call super in the controller and customise instead of overwriting everything :(


UPDATE


My User model:

class User < ApplicationRecord    devise .......    has_and_belongs_to_many :roles  end  

My Role model:

class Role < ApplicationRecord    has_and_belongs_to_many :users  end  

My schema:

create table "users" ....    t.stuff ....    ....  end    create table "roles" ....    t.stuff ....    ....  end    create table "user_roles" ...    t.integer "user_id"    t.integer "role_id"  end  

Updating city state list in rails app

Posted: 22 Oct 2016 03:20 AM PDT

I m using city state gem in my rails app However I do realize that the list of cities or states of most countries outside of the US isn't complete. How do I add or update these list to complete what I want. Can I also even correct some naming of cities that are wrong From a code like this:

%select{name: "state"}  - CS.states(:cn).each do |key, value|  %option{:value => key}= value  

I get a list of cities and provinces all together. some are even missing and i would like to correct that. Any suggestion

rails heroku "production.rb" file

Posted: 22 Oct 2016 02:49 AM PDT

When I change "config.assets.compile" to true in "production.rb" my images show on heroku. But when I set it to false they won't show. I was under the impression that you either set it to true and don't "rake assets:precompile", or you set it to false and do "rake assets:precompile". But it seems the images only show when i set it to true. What's going on here?

error: failed to push some refs to 'https://git.heroku.com/radiant-chamber-18560.git'

Posted: 22 Oct 2016 05:59 AM PDT

I run these commands

  1. heroku create
  2. git push heroku master

error information

Then.

  1. git remote add heroku https://git.heroku.com/radiant-chamber-18560.git
  2. git push heroku master

error information

What should I do?

Fragment caching for each session id separetely, Rails 4 + Ransack

Posted: 22 Oct 2016 01:00 AM PDT

I want to cache search block for each user/visitor separately so when user/visitor has searched or sorted for anything search block is cached with all CSS and visual changes. So when user revisits Advertisement#index page in 5.minutes Rails cache renders the same search block as he left.

Previously, I tried to count clicks on sort links and then save them as cookies and then when Advertisement#index page is loaded, make all clicks. But that approach was very nasty and didn't work sometimes.

Search block: enter image description here

So far I have successfully cached search results and retrieving them based on session.id.

My code in Advertisement_controller:index :

  if params[:q].present?  #if search params is present            @cache_search = true  #this is for fragment cache in view           Rails.cache.delete("q_#{request.session.id}")           Rails.cache.write("q_#{request.session.id}",params[:q],:expires_in => 5.minutes)                  @search = @adver.search(params[:q])          else            params[:q] = Rails.cache.read("q_#{request.session.id}")            @search = @adver.search(params[:q])              end            @search.sorts = ['height asc','age asc','votes_for.size asc'] if @search.sorts.empty?          @advertisements = @search.result(distinct: true)           #delete cache is search resulted in 0 results        if @advertisements.present?        else             Rails.cache.delete("q_#{request.session.id}")        end  

This code generates this cache: q_925feaae9c1cd1f6948899e672838c0a.

My search block:

<% cache_if @cache_search == true, request.session.id do %>      <%= search_form_for @search, :class=>"search",:id=>"search-menio",:remote=>"true", url: girls_path, :method => :get do |f| %>              <%= f.text_field :name_or_phone_number_or_identifier_cont, :id=>"search-field-keyup",:class=>"form-control-s" %>            <%end%>              <%= sort_link(@search, :height,t('height'),{hide_indicator: true},{ :remote => true, :method => :get }) %>              <%= sort_link(@search, :age,t('age'),{hide_indicator: true},{ :remote => true, :method => :get }) %>              <%= sort_link(@search, 'votes_for.size',t('rating'), {hide_indicator: true},{ :remote => true, :method => :get }) %>           <%end%>  <%end%>  

Problem: Rails wont cache search block when search occurs, but when I first time visit Advertisement#index page. How could edit my code so search block cache is renewed each time search occurs and serve this cached search block for 5.minutes or new search ?

I have searched for similair questions, but none was like mine.

Thanks for any help.

Uploading/playing mp3 files using Rails

Posted: 22 Oct 2016 03:47 AM PDT

I'm working on my first "real" Rails project - "modernizing" an old website for a church choir and am building it in Rails. They currently have a practice page with a list of links to mp3 files stored on their server. I would like to store the mp3 files in a database and have created a model for the songs - title:string, part:string (tenor, soprano, etc), audio:binary (this is the mp3 file). When I submit the form, the audio field is nil - the other fields save correctly. Should I be using a Gem for uploading/saving the mp3 files? I've come across CarrierWave, but have only seen it used with images. I was under the impression that the binary field in active record was for preserving the original file format. Thanks in advance!

Where is the Redmine plugin generator? How to create a new plugin?

Posted: 22 Oct 2016 12:39 AM PDT

I am newbie to redmine want to create redmine plugin . Whether I need to create new project and then execute steps listed here ?

http://www.redmine.org/projects/redmine/wiki/Plugin_Tutorial

Or any other good document that I can follow .

Heroku Everything Up-To-Date

Posted: 22 Oct 2016 06:00 AM PDT

So i've googled this error messages and went through the various stack overflow posts with regards to this. My issue came yesterday when the Dyn DNS were under a DDoS attack. Anyway the initial problem was that when i tried doing git push heroku master it constantly returned everything up-to-date

I tried everything i found in the various relevant stack overflow posts. From doing git remote rm heroku then adding it back, to checking out a new branch then doing git push heroku <branch name>:master but nothing worked.

After trying various other things i gave up and decided to simply delete my heroku app and try pushing all over.

Now the weird thing (which may just be my lack of understanding of how all these works) would be even after deleting my app and not creating a new one, when i run the command git push heroku master it still returns everything up-to-date. Why is that so when there is no longer any app there?

Additionally i have also tried heroku create before trying to push it and it returns everything up-to-date as well. I read that everything is up and running on heroku's side so i'm not quite sure what is the problem.

I can't seem to find any updated documentation on this issue as well so i'm hoping that someone can point me in the right direction or steps to take.

How to send mails automatically using whenever gem

Posted: 22 Oct 2016 01:13 AM PDT

I used when ever gem to send mails every day but it's not sending.I am using amazon linux ec2 instance. Please look at my code once.

schedule.rb:

every 5.minutes do    runner "Listings.today_expired_spaces"  end  

Listings.rb:(model-file)

  def today_expired_spaces          @list=List.find_by_date(Date.today)          UserMailer.today_expired_list(@list).deliver      end  

In production:

After running these commands I am getting responses like this

1.whenever -w

[write] crontab file written

2.whenever -i [write] crontab file updated

3.whenever

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash -l -c 'cd /home/ubuntu/my_server && bundle exec script/rails runner -e production '\''Spaces.today_expired_spaces'\'''

[message] Above is your schedule file converted to cron syntax; your crontab file was not updated.

[message] Run `whenever --help' for more options.

Please provide solution to this.

Ruby on Rails 4: Where i have to put Common code?

Posted: 22 Oct 2016 04:39 AM PDT

I am new to Ruby on rails. i am using rails 4.1.6 and what i want is to make log of all the process in one text file (like index page accessed, view page access etc..). for that i want to create common function, in which i can pass my text as agrs, i had do some R&D on that and i found this : In Rails, where to put useful functions for both controllers and models, but it seems that it is not working with active admin resources. so, for active admin controller and model, i have to create any other modules (i.e. on other location let say /admin/) or anything else i have to do ?

is there any global location that we can use in active admin like component in cakephp.

thanks

EDIT

app/admin/driver.rb

ActiveAdmin.register User, as: 'Driver' do      ...      ...      index :download_links => false do          ...          ...          #call function to maintain log something like,          take_note('action performed')      end  

rails excel generation - alignment of column text

Posted: 21 Oct 2016 11:45 PM PDT

I export a excel through rails app using gem "axlsx_rails" and 'acts_as_xlsx'. Here my doubt is why the numbers are aligned as right alignment and alphabets are aligned as left alignment in spreadsheet columns.
In my sheet I have the column as admission number (ad.no). It's the mixture of alphabets and number like A123 as well as like 123. If I export these to excel, the ad.no A123 aligned at right of column and 123 aligned at left of the column. I want to align all the ad.no at left or right of the column. Can anyone please explain and give solution to how to align that column.
Thanks.

How to reduce external API calls in rails

Posted: 21 Oct 2016 10:48 PM PDT

I have integrated facebook, twitter API's in my rails application for getting hashtag records. Everything is working fine but API calls are taking too long too execute which is really very frustrating. I googled around to get rid of this. There are curl_multi functions available in PHP. Is there something available in rails too?

Scrapping data in rails using thread

Posted: 21 Oct 2016 11:21 PM PDT

I am doing scraping to fetch the data from the website to my database in rails.I am fetching the 32000 record with this script there isn't any issue but i want to fetch the data faster so i apply the thread in my rake task but then there is a issue while running the rake task some of the data is fetching then the rake task getting aborted.

I am not aware of what to do task if any help can be done i am really grateful . Here is my rake task code for the scraping.

task scratch_to_database: :environment do    time2 = Time.now    puts "Current Time : " + time2.inspect      client = Mechanize.new      giftcard_types=Giftcard.card_types      find_all_merchant=Merchant.all.pluck(:id, :name).to_h        #first index page of the merchant      index_page = client.get('https://www.twitter.com//')      document_page_index = Nokogiri::HTML::Document.parse(index_page.body)      #set all merchant is deteled true      # set_merchant_as_deleted = Merchant.update_all(is_deleted: true) if Merchant.exists?      # set_giftcard_as_deleted = Giftcard.update_all(is_deleted: true) if Giftcard.exists?      update_all_merchant_record = []      update_all_giftcard_record = []      threads = []      #Merchant inner page pagination loop      page_no_merchant = document_page_index.css('.pagination.pagination-centered ul li:nth-last-child(2) a').text.to_i      1.upto(page_no_merchant) do |page_number|          threads <<   Thread.new do          client.get("https://www.twitter.com/buy-gift-cards?page=#{page_number}") do |page|              document = Nokogiri::HTML::Document.parse(page.body)                #Generate the name of the merchant and image of the merchant loop              document.css('.product-source').each do |item|                 merchant_name= item.children.css('.name').text.gsub("Gift Cards", "")                  href = item.css('a').first.attr('href')                  image_url=item.children.css('.img img').attr('data-src').text.strip                    #image url to parse the url of the image                   image_url=URI.parse(image_url)                   #saving the record of the merchant                  #  @merchant=Merchant.create(name: merchant_name , image_url:image_url)                    if find_all_merchant.has_value?(merchant_name)                      puts "this if"                      merchant_id=find_all_merchant.key(merchant_name)                      puts merchant_id                    else                      @merchant= Merchant.create(name: merchant_name , image_url:image_url)                      update_all_merchant_record << @merchant.id                      merchant_id=@merchant.id                    end                  # @merchant.update_attribute(:is_deleted,  false)                  #set all giftcard is deteled true                  # set_giftcard_as_deleted = Giftcard.where(merchant_id: @merchant.id).update_all(is_deleted: true) if Giftcard.where(merchant_id: @merchant.id).exists?                   #first page of the giftcard details page                  first_page = client.get("https://www.twitter.com#{href}")                  document_page = Nokogiri::HTML::Document.parse(first_page.body)                  page_no = document_page.css('.pagination.pagination-centered ul li:nth-last-child(2) a').text.to_i                  hrefextra =document_page.css('.dropdown-menu li a').last.attr('href')                    #generate the giftcard details loop with the pagination                  # update_all_record = []                 find_all_giftcard=Giftcard.where(merchant_id:merchant_id).pluck(:row_id)                 puts merchant_name                 #   puts find_all_giftcard.inspect                           card_page = client.get("https://www.twitter.com#{hrefextra}")                       document_page = Nokogiri::HTML::Document.parse(card_page.body)                         #table details to generate the details of the giftcard with price ,per_off and final value of the giftcard                         document_page.xpath('//table/tbody/tr[@class="toggle-details"]').collect do |row|                         type1=[]                           row_id = row.attr("id").to_i                           row.at("td[2] ul").children.each do |typeli|                         type = typeli.text.strip if typeli.text.strip.length != 0                         type1 << type if typeli.text.strip.length != 0                         end                             value = row.at('td[3]').text.strip                           value = value.to_s.tr('$', '').to_f                             per_discount = row.at('td[4]').text.strip                           per_discount = per_discount.to_s.tr('%', '').to_f                             final_price = row.at('td[5] strong').text.strip                           final_price = final_price.to_s.tr('$', '').to_f                             type1.each do |type|                              if find_all_giftcard.include?(row_id)                                update_all_giftcard_record<<row_id                                puts "exists"                              else                                puts "new"                             @giftcard= Giftcard.create(card_type: giftcard_types.values_at(type.to_sym)[0], card_value:value, per_off:per_discount, card_price: final_price, merchant_id: merchant_id , row_id: row_id )                             update_all_giftcard_record << @giftcard.row_id                             end                           end                           #saving the record of the giftcard                             # @giftcard=Giftcard.create(card_type:1, card_value:value, per_off:per_discount, card_price: final_price, merchant_id: @merchant.id , gift_card_type: type1)                       end                       # Giftcard.where(:id =>update_all_record).update_all(:is_deleted => false)                    #delete all giftcard which is not present                  # giftcard_deleted = Giftcard.where(:is_deleted => true,:merchant_id => @merchant.id).destroy_all if Giftcard.where(merchant_id: @merchant.id).exists?            time2 = Time.now            puts "Current Time : " + time2.inspect              end          end          end      end      threads.each(&:join)          puts "-------"          puts threads      # merchant_deleted = Merchant.where(:is_deleted => true).destroy_all if Merchant.exists?      merchant_deleted = Merchant.where('id NOT IN (?)',update_all_merchant_record).destroy_all if Merchant.exists?      giftcard_deleted = Giftcard.where('row_id NOT IN (?)',update_all_giftcard_record).destroy_all if Giftcard.exists?  end  

end

Error i am receiving: ActiveRecord::ConnectionTimeoutError: could not obtain a connection from the pool within 5.000 seconds (waited 5.001 seconds); all pooled connections were in use

How to view excel sheets in rails4 without downloading/using googledoc/microsoft office docs

Posted: 22 Oct 2016 03:22 AM PDT

In my rails-4 application, I need to show the excel(xls,xlsx) file contents without using external services. The external services will be available if the documents are public. Without downloading I need to open the excel attachments. Is there any way to do this in rails. Please help.

Thanks in advance.

Fetch Game with time of EST Timezone

Posted: 22 Oct 2016 12:33 AM PDT

I have Game table, from which I want to fetch game which started in time between 11:00:00 to 14:00:00. But my start_in_time stored in database is in UTC. And I want to fetch games started time 11:00:00 EST and 14:00:00 EST.

Game.where("Time((start_in_time at time zone 'UTC') at time zone 'EST') between '11:00:00' and '14:00:00' ")  

I have used mysql as database above query but in database I am getting syntax error. How to make this correct ?

Having trouble using where.not in rails

Posted: 21 Oct 2016 09:35 PM PDT

I am trying to use where.not to replace the following:

if @friend_matches.count > 0    @court_matches = Match.available_on_courts.where('matches.id NOT IN (?)', @friend_matches.pluck(:id)).to_a  else    @court_matches = Match.available_on_courts  end  

With

    @court_matches = Match.available_on_courts.where.not(matches.id: @friend_matches.pluck(:id)).to_a  

However I am getting the following errors.

SyntaxError: /Users/sripaladugu/Coding/matchpoint_rails/app/mailers/match_mailer.rb:8: syntax error, unexpected ':'  ...on_courts.where.not(matches.id: @friend_matches.pluck(:id))....  ...                               ^  /Users/sripaladugu/Coding/matchpoint_rails/app/mailers/match_mailer.rb:8: syntax error, unexpected ')', expecting keyword_end  ...id: @friend_matches.pluck(:id)).to_a  

Rails+Devise: No error message is shown

Posted: 21 Oct 2016 09:46 PM PDT

I'm making rails + Devise + Bootstrap app. Basically it seems like working well, but when it gets wrong password , no error message is shown like this. enter image description here

I can't figure out why it happened and how to fix it. Could you give me any advise for that? Thanks in advance!

Ruby on Rails installation on Windows via Proxy

Posted: 21 Oct 2016 08:39 PM PDT

i try but can do this ...

how to set proxy , really i don't know

also see stack overflow and other forums... here links:

Issue installing gems on windows 7 with proxy

but can not get it how to set variable , which proxy give(ip..browser or other) and how set port , plz can anyone simple way explain how to solve...

Thanks in advance...!!! ERROR: While executing gem ... (URI::InvalidURIError) bad URI(is not URI?): http://http_proxy = username:password@proxyserver:port

Why the "post request" defined to "button_to" as default turns to "get request" only after we restart the rails server?

Posted: 21 Oct 2016 08:25 PM PDT

|| Ruby 2.2.4 || Rails 5.0 || Bootstrap-sass 3.3.7 || Devise 4.2 ||

I am one of many programming learners having problems with the button_to in ruby on rails and the solution is add the method ":get", but what most of us don't know is about the obligate server restart! At least with functions like destroy and edit, this is the only way to fix the button_to issue !

I would like to understand why the server have to be restarted?

How to keep attributes from two different tables synchronized in RoR?

Posted: 21 Oct 2016 10:27 PM PDT

What I want is to be able to easily be able to find the team name associated with a membership without having to send another request to the database. My plan was to just add a team_name attribute to the Memberships table, but I can't think of a way to have this new attribute stay in sync with the name attribute in the Teams table. In other words, I want it to be the case that, if the owner of a team changes the team's name, then all memberships to that team will be updated (with the new team name) as well.

Here is what my setup looks like. I've fairly new to Rails.

/app/models/membership.rb

class Membership < ActiveRecord::Base    belongs_to :user    belongs_to :team  end  

/app/models/team.rb

class Membership < ActiveRecord::Base    belongs_to :user    belongs_to :team  end  

/app/db/schema.rb

ActiveRecord::Schema.define(version: 20161022002620) do      create_table "memberships", force: :cascade do |t|      t.integer  "user_id"      t.integer  "team_id"      t.datetime "created_at"      t.datetime "updated_at"    end      create_table "teams", force: :cascade do |t|      t.string  "name"      t.integer "user_id"    end  end  

If there is a better way to achieve what I am asking, then please let me know as well.

Keeping track of state of model data

Posted: 21 Oct 2016 07:26 PM PDT

I want to track positions and portfolio value over time in my portfolio in order to present them on a graph. My portfolio has many positions. Positions store stock price and quantity. Each position has many movements that either buy or sell quantities of shares of stock. The problem is my application updates the price every day to reflect current market prices. And I can also change the quantity to remove or add quantity of shares. I calculate portfolio value by taking the total of stock price x quantity for each position.

I want to be able to do two things 1) Store values of portfolios over time and plot them on a graph 1) Store values of positions over time and plot them on a graph

class Portfolio < ApplicationRecord    has_many :positions, dependent: :destroy    has_many :movements, through: :positions    belongs_to :user    ...    class Position < ApplicationRecord    belongs_to :portfolio    has_many :movements, dependent: :destroy    ...    class Movement < ApplicationRecord    belongs_to :position    validates :quantity, presence: true    ...  

I am thinking of creating a chart-object model that will simply take a snapshot/store the positions and portfolio values at the end of each business day and I can then use that model to populate a graph.

Is this the best design decision or is there a more efficient way to store/ track the data through states?

In Rails Console, Is there a way to disable or shorten the error path list?

Posted: 21 Oct 2016 08:14 PM PDT

Here is an example of what I am seeing:

enter image description here

Can't persist array in a Postgres column using Active Record

Posted: 21 Oct 2016 05:20 PM PDT

I know this question may sound duplicated, but none of the solutions I've found actually solved my problem.

I have a model named pet with photos column, here's my schema:

t.string "photos", default: [], array: true  

I'm not using the serialize method in my class because a lot of other sources confirmed that it's not necessary.

Here's my object:

#<Pet id: 9, name: nil, age: nil, vaccinated: nil, male: nil, pet_description: nil, additional_info: nil, size: nil, neutered: nil, classified_id: nil, created_at: "2016-10-21 23:36:37", updated_at: "2016-10-21 23:55:50", kind: nil, photos: []>  

No matter I do, I cannot persist a new photo array:

UPDATE "pets" SET "updated_at" = $1, "photos" = $2 WHERE "pets"."id" = $3  [["updated_at", 2016-10-21 23:51:30 UTC], ["photos", "{}"], ["id", 9]]  

I've already tried several ways of persisting, like:

model.array << element  model.array_will_change!  model.save!    

or even (like this guy suggested, and this other guy as well):

update_attributes locations: locations + [ place ]  

and none of them seems to work.

Using Postgres command line I was able to save and update and array with no problems, but this issue seems to be related to active record.

activerecord (5.0.0.1) postgres (9.6.0.0)

Thanks a lot :-)

No comments:

Post a Comment