Why might a form.html.erb not be able to read a password? Posted: 03 Nov 2016 07:35 AM PDT I'm working on my first ruby on rails projects and I've run into a problem. Basically when I try to input a new user (or in my case an employer or a candidate) or edit a current one it fails to read the password, it says; "2 errors prohibited this employer from being saved: Password can't be blank. Password digest can't be blank." Any ideas where to even start looking for the error, everything seems fine to me. I'll post whatever pages are required to look into the problem. |
Cannot replace association in has_one, belongs_to relationship in rails Posted: 03 Nov 2016 07:35 AM PDT I am attempting to destroy the relationship between two models in a has_one/belongs_to relationship, but I do not want to destroy either indivual models. I have a project and that project has a domain. The domains can be purchased during the creation of a project, or they can be fully realized beforehand. If a user wishes to change the domain associated with a project, they must be able to keep the old domain for re-use later. The set up is like this: class CustomDomain < ActiveRecord::Base belongs_to :user belongs_to :project class User < ActiveRecord::Base has_many :projects has_many :custom_domains class Project < ActiveRecord::Base belongs_to :user has_one :custom_domain When I attempt to change the domain associated with a project, I get the message: Failed to remove the existing associated custom_domain. The record failed to save when after its foreign key was set to nil. I want to be able to remove an association, but keep all the models involved. I have found people with similar problems, such as this one but they want to actually destroy the models. Can someone please help? Should the relationship be that a project has_one :through user? |
Is there a lazy select_all option in Rails? Posted: 03 Nov 2016 07:40 AM PDT I've got a complicated query that I need to run, and it can potentially yield a large result set. I need to iterate linearly through this result set in order to crunch some numbers. I'm executing the query like so: ActiveRecord::Base.connection.select_all(query) find_in_batches Won't work for my use case, as it's critical that I get the records in a custom order. Also, my query returns some fields that aren't part of any models, so I need to get the records as hashes. The problem is, select_all is not lazy (from what I can tell). It loads all of the records into memory. Does Rails have a way to lazily get the results for a custom SQL query? .lazy doesn't seem applicable here, as I need custom ordering of the results. This is possible in other languages (C#, Haskell, JavaScript), so it seems like it would be possible in Ruby. |
Rails group and show oldest and latest value Posted: 03 Nov 2016 07:45 AM PDT This question is related to this question I asked previously. database table servers: date, server_id, server_name, server_status By using this in my controller: @servers = Server.order(date: :desc).group(:server_id) I can show latest server status in my view with: <td><%= server.server_status %></td> How can I show on same table in view the first status too? Basically by ordering by date in the opposite way. I know it doesn't really make sense in this context but I used the example in the first question to make it clearer. Thanks in advance |
select posts from one day Posted: 03 Nov 2016 07:37 AM PDT I want to select posts from one day. What is the correct way? This errors: date = '3/11/2016'.to_date User.joins(:posts).where(posts: {'created_at >= ? AND created_at <= ?', date.beginning_of_day, date.end_of_day}) |
Ruby Appending comment block to YAML file Posted: 03 Nov 2016 07:43 AM PDT I have a yml file that I am using to store a list of stories I have added between releases. I am using a rake task to dynamically update the version number based off what stories I have added to this file. It is introducing a new process, so I created the following comment block this will help anyone commenting here to add stories in the right format: # Version control file. # Versions should be incremented as follows # # [X - major change] . [V - new feature] . [I - Bug fix / Small change] # # Update the undefined block with a one line readable description of what your story was about. example: # # undefined: # stories: # - "I - fixed spelling mistake" # - "V - added import functionality" # - "X - rebuilt the main dashboard" # The issue is after my rake task is done the job the file loses the comment block. I pretty much load the YAML versions = YAML.load_file( 'doc/release.yml' ) and then once the logic is finished I File.open("doc/release.yml", 'w') { |f| YAML.dump(versions, f) } Where versions is the new updated hash. However, this removes the comment block to the file. Other solutions I have found just modify existing lines. Is there a way to open the file and adding the above without messing up the YAML beneath. Any help will be much appreciated. |
Favorite action getting error: Wrong number of arguments (given 1, expected 0)? Posted: 03 Nov 2016 07:13 AM PDT I had a working favorite action where my users could favorite a room but now I'm getting this error and I dont know why it is not working? How can I make this work? show.html.erb <% if current_user && current_user.favorites.exists(@room) %> <%= link_to "unfavorite", favorite_room_path(@room, type: "unfavorite"), method: :put %> <% else %> <%= link_to "favorite", favorite_room_path(@room, type: "favorite"), method: :put %> <% end %> rooms_controller.rb before_action :set_room, only: [:show, :favorite] before_action :authenticate_user!, only: [:favorite] def show @photos = @room.photos @booked = Reservation.where("room_id = ? AND user_id = ?", @room.id, current_user.id).present? if current_user @reviews = @room.reviews @hasReview = @reviews.find_by(user_id: current_user.id) if current_user end def favorite type = params[:type] if type == "favorite" current_user.favorites << @room unless current_user.favorites.exists?(@room) redirect_to wishlist_path, notice: 'You favorited #{@room.listing_name}' elsif type == "unfavorite" current_user.favorites.delete(@room) redirect_to wishlist_path, notice: 'Unfavorited #{@room.listing_name}' else # Type missing, nothing happens redirect_to wishlist_path, notice: 'Nothing happened.' end end private def set_room @room = Room.find(params[:id]) end |
Active Record returns null when aliasing primary_key as "id" Posted: 03 Nov 2016 07:12 AM PDT I want to alias DB fields, but aliasing primary_key as "id" will blank its value: class XXX < ActiveRecord::Base self.table_name = 'XXX' self.primary_key = 'xxx_id' def self.get() self.select( primary_key + ' AS id', 'xxx_itmno AS product_number', 'xxx_qty AS qty' ) end Output: [{ id: null, product_number: 123, qty: 2 }] Question 1. What's the easiest way to workaround this issue? Question 2. Why this is happening? PS #1: The issue goes away if I alias as something else. i.e. primary_key + 'AS id_' , which will output: [{ id_: 42, product_number: 123, qty: 2 }] PS #2: I find that including PK also will work: self.select( primary_key, primary_key + ' AS id', ... Output: [{ xxx_id: 42, id: 42, product_number: 123, qty: 2 }] But, I would have to post-process removing the PK. |
How would one send a String from C to Ruby on Rails app over a network? Posted: 03 Nov 2016 07:17 AM PDT I have a String generated in C indicating low level platform details of the client, and I need to send this String to a server which will be receiving it through a Rails app. How can I achieve this? [upvotes requested so I may get an answer soon] |
How to execute function after user is locked, Rails 4 and Devise Posted: 03 Nov 2016 06:51 AM PDT I have set up lockable function and it works perfectly after 10 failed attempts. I want to execute some code right after user account is locked due failed attempts. Code what I want to execute: Banlist.new Banlist.ip_adress = request.remote_ip Banlist.save Basically, I want to catch the last IP address that unsuccessfully tried to log in (10x attempt). What I have tried: In user model: after_update :set_ip def set_ip if self.locked_at == 'nil' else Banlist.new Banlist.ip_adress = request.remote_ip Banlist.save end end Unfortunately, this code is not working as request.remote_ip requires HTTP request to catch IP address. In Devise Github page I found devise/lib/devise/models/lockable.rb file with fallowing line: def lock_access!(opts = { }) self.locked_at = Time.now.utc if unlock_strategy_enabled?(:email) && opts.fetch(:send_instructions, true) send_unlock_instructions else save(validate: false) end end I could add my code here, but I can't find this lockable.rb file in my Rails app directory. Question: What could be the best way to catch when user account is locked and execute some code ? Thanks in advance for any help. |
RoR Adding object to an array already in def initialize? Posted: 03 Nov 2016 07:15 AM PDT This is my first attempt with Ruby on Rails, so I apologize if the question is obvious, but unfortunately I can not find the answer anywhere. class Client < Person clientList = [] def initialize(name, surname, email, wallet) super(name, surname, email) @wallet = wallet end attr_reader :wallet, :clientList def to_s super + ", #{@wallet}" end def add_to_array clientList + this.object #i know its not correct end end I would like to create method, which allow me to add instances of client class to clientList array. What else is there later any option to use this method already in def initialize(name, surname, email, wallet) . Something like this.add_to_array I would like to have array with all clients inside, but i don't want to use method add_to_array everytime i create new client. It should be automatic. |
Form hidden fields and security Posted: 03 Nov 2016 07:26 AM PDT I m using hidden field in my app to add user_id to my database "Camping". I have associations "User" has many campings and "Camping" belongs_to "user". When I run firebug or something like this, I can modify user_id value of this field. If any user puts his ID, I can modify object to other user... I want to avoid this ! My code <%= f.hidden_field :user_id, :value => current_user.id %> This code, is necessary because I allow only user to edit / updated / create object if they have user_id == current_user.id. How to fix this security problem ? By the way, I m using devise. Edit with full code My _form.html.erb <%= form_for(camping) do |f| %> <% if camping.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(camping.errors.count, "error") %> prohibited this camping from being saved:</h2> <ul> <% camping.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <%= f.hidden_field :user_id, :value => current_user.id %> <div class="form-group"> <label for="name">Nom du camping</label> <%= f.text_field :name, autofocus: true, class:"form-control", id:"name", :required => true%> </div> <div class="actions"> <%= f.submit "Enregistrer", class:"btn btn-success" %> </div> <% end %> my controller def new @camping = Camping.new @campings = Camping.all end def edit end def create @camping = Camping.new(camping_params) respond_to do |format| if @camping.save format.html { redirect_to @camping, notice: 'Camping was successfully created.' } format.json { render :show, status: :created, location: @camping } else format.html { render :new } format.json { render json: @camping.errors, status: :unprocessable_entity } end end end def update @camping = Camping.find(params[:id]) respond_to do |format| if @camping.update(camping_params) format.html { redirect_to @camping, notice: 'Camping was successfully updated.' } format.json { render :show, status: :ok, location: @camping } else format.html { render :edit } format.json { render json: @camping.errors, status: :unprocessable_entity } end end end my edit.html.erb <div class="containershow"> <h1>Editing Camping</h1> <%= render 'form', camping: @camping %> <%= link_to 'Show', @camping %> | <%= link_to 'Back', campings_path %> </div> my new.html.erb <h1>New Camping</h1> <%= render 'form', camping: @camping %> <%= link_to 'Back', campings_path %> |
Make Gem initializer run after an application-specific initializer Posted: 03 Nov 2016 06:43 AM PDT I'm developing a Gem that can be configured by creating an application-specific initializer, say config/initializers/my_gem.rb . The Gem also includes its own initializer, and this one has to run after the application-specific initializer is run (as it uses the set-up of the other initializer). The Gem initializer is created as follows: module MyGem class Railtie < ::Rails::Railtie initializer 'my_gem.internal_setup' do end end end The problem is that the Gem initializer always runs first. I've even tried renaming it to zzz or using after: :my_gem , but it's still called first. Before digging through the Rails source: Does anyone know why this is not called in alphabetical order and why the after: doesn't work? |
How to shorten Exception Handling Message in Rails? [Rails 5.0] Posted: 03 Nov 2016 07:11 AM PDT i am working on a Rails project and using Exceptions Handling in it, i am using it like this: begin @profile.update(profile_params) flash[:success] = SUCCESS_MESSAGE_FOR_PROFILE_UPDATED redirect_to params[:referrer] rescue => e flash[:alert] = "#{e.message}" render :edit end when exception occurs, it generates a very long message: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_companies_on_name" DETAIL: Key (name)=(Test2) already exists. : UPDATE "companies" SET "name" = $1, "updated_at" = $2 WHERE "companies"."id" = $3 as we can see that the exception occurred due to duplicate entry for 'name', So basically i just want to show the DETAIL part i.e. "Key (name)=(Test2) already exists." Now the question is how to do this. Please help me to sort out this issue. Thanks. |
How to scrape and import data to existing db? Posted: 03 Nov 2016 06:26 AM PDT I just finished my first rails app, a yelp clone. Now I want to scrape data from yelp or use a webcrawler to add their data to my database. I have looked into scraping it and saving it to a excel then using the gem roo to read the excel file but I'm unsure this would work. I have looked into Nokogiri but I'm unsure if this will work. I have seen some web crawlers gems too, but I am unsure if they are what I need. Getting the images I have no idea how to do, also to get data from several pages maybe 20. I want to add all restaurants in Atlanta but I'm unsure if I can make that many calls without getting in trouble or having to pay. The required fields I need are. Name Address Phone Website Image Here is my app: https://yelping-it-up.herokuapp.com/ Any additional information is appreciated. |
Resque `before_fork` not called but `before_first_fork` is Posted: 03 Nov 2016 06:06 AM PDT I am adding Resque to a Rails 5 application, and I am trying to redirect the logs to file, instead of to STDIO . I have the following in an initializer: Resque.before_first_fork do puts "Call me once before the worker forks the first time" end Resque.before_fork do puts "Call me once before the work forks any time" end I want to add the following so that workers write to log file: # Open the new separate log file logfile = File.open(File.join(Rails.root, 'log', 'resque.log'), 'a') # Activate file synchronization logfile.sync = true # Create a new buffered logger Resque.logger = ActiveSupport::BufferedLogger.new(logfile) Resque.logger.level = Rails.logger.level Resque.logger.info "Resque Logger Initialized!" I have read a lot of resources on using before_fork , but nothing in that block is being executed. Why would this be the case, is before_first_fork okay to use as a substitute. I would appreciate any help. I am starting the worker in my dev env with: QUEUE=default rake resque:work |
Issue with saml_idp Rails gem, undefined method `authn_request?' Posted: 03 Nov 2016 06:05 AM PDT So I'm using this gem for SAML. Serivce provider is already set and connected in the initializer, and I have this in my controller. class SamlIdpController < SamlIdp::IdpController skip_before_filter :validate_saml_request, only: [:new, :create] def idp_authenticate(email, password) user = User.find_by_email(email) user && user.valid_password?(password) ? user : nil end private :idp_authenticate def idp_make_saml_response(found_user) encode_response found_user end private :idp_make_saml_response end When I try to login, I get this error: F, [2016-11-03T14:58:50.416637 #15024] FATAL -- : NoMethodError (undefined method `authn_request?' for nil:NilClass): app/controllers/saml_idp_controller.rb:13:in `idp_make_saml_response' The official wiki of the gem is pretty straight forward. I also tried passing 'user' instead of 'found_user' but getting the same error. What does that method expects? I'm I missing something here? Any help is welcomed. Thanks! |
How to use environment variable to avoid hard-coding postgresql's username and password in database.yml? Posted: 03 Nov 2016 07:11 AM PDT I created a new Rails app called sample_app and I use postgresql as my db (I already created a postgresql username and password). I use this setup guide https://gorails.com/setup/ubuntu/16.04 So I run this command rails new sample_app -d postgresql . And then I have to edit the config/database.yml to match the username and password to my postgresql's username and password I just created. But I don't want to hard-code because I will be using git. I found this tutorial from digital ocean which suggest to use: username: <%= ENV['APPNAME_DATABASE_USER'] %> password: <%= ENV['APPNAME_DATABASE_PASSWORD'] %> Is this the correct code? If so, since my app is called sample_app, my code should be? username: <%= ENV['SAMPLE_APP_DATABASE_USER'] %> password: <%= ENV['SAMPLE_APP_DATABASE_PASSWORD'] %> If this is not the correct one, can you help me? Thank you! |
Rails 'ascii' codec can't decode byte 0xd0 in position 14: ordinal not in range(128) Posted: 03 Nov 2016 05:50 AM PDT So I have problem, when I try start my playbook have this message : Using /etc/ansible/ansible.cfg as config file ERROR! Unexpected Exception: 'ascii' codec can't decode byte 0xd0 in position 14: ordinal not in range(128) the full traceback was: Traceback (most recent call last): File "/usr/bin/ansible-playbook", line 103, in <module> exit_code = cli.run() File "/usr/lib/python2.7/dist-packages/ansible/cli/playbook.py", line 159, in run results = pbex.run() File "/usr/lib/python2.7/dist-packages/ansible/executor/playbook_executor.py", line 81, in run pb = Playbook.load(playbook_path, variable_manager=self._variable_manager, loader=self._loader) File "/usr/lib/python2.7/dist-packages/ansible/playbook/__init__.py", line 53, in load pb._load_playbook_data(file_name=file_name, variable_manager=variable_manager) File "/usr/lib/python2.7/dist-packages/ansible/playbook/__init__.py", line 61, in _load_playbook_data self._basedir = os.path.normpath(os.path.join(self._basedir, os.path.dirname(file_name))) File "/usr/lib/python2.7/posixpath.py", line 80, in join path += '/' + b UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 14: ordinal not in range(128) This my playbook : --- - hosts: 'all' remote_user: 'root' # В данном блоке объявляются переменные, которые будут использоваться в playbook и конфигах, представленных выше vars: # Версия ruby ruby_version: '2.2.1' # Пользователь, от лица которого будет происходит деплой user: 'rinykia' # Домашняя директория home: '/home/{{ user }}' # Директория установки Rbenv rbenv_root: '{{ home }}/.rbenv' # Название приложения name: 'new-app' # Путь до нашего приложения application: '{{ home }}/applications/{{ name }}' # Список задач, которые будут выполнены последовательно tasks: # Обновление кеша и установка необходимых пакетов, всего программного обеспечения, # необходимого для работы нашего сервера - name: 'apt | update' action: 'apt update_cache=yes' - name: 'apt | install dependencies' action: 'apt pkg={{ item }}' # with_items - это обычный цикл в Ansible, он возьмёт и прогонит все его элементы через action with_items: - 'build-essential' - 'libssl-dev' - 'libyaml-dev' - 'libreadline6-dev' - 'zlib1g-dev' - 'libcurl4-openssl-dev' - 'git' - 'nginx' - 'redis-server' - 'postgresql' - 'postgresql-contrib' - 'libpq-dev' - 'imagemagick' - 'libmagickwand-dev' - 'nodejs' - 'htop' # Создаём нашего пользователя deploy, копируем авторизационный ключ, # а так же публичный и приватный ssh ключи - name: 'account | create' user: 'name={{ user }} shell=/bin/bash' - name: 'account | copy authorized keys' # shell - это модуль Ansible, который позволяет выполнять обычные bash команды shell: 'mkdir -p {{ home }}/.ssh -m 700 && cp /root/.ssh/authorized_keys {{ home }}/.ssh && chown -R {{ user }}:{{ user }} {{ home }}/.ssh' - name: 'account | copy ssh private key' # Модуль copy просто берёт и копирует файл из папки src в папку dest copy: 'src=keys/id_rsa dest={{ home }}/.ssh/id_rsa owner={{ user }} group={{ user }} mode=0600' - name: 'account | copy ssh public key' copy: 'src=keys/id_rsa.pub dest={{ home }}/.ssh/id_rsa.pub owner={{ user }} group={{ user }} mode=0644' # Устанавливаем ruby-build, rbenv, bundler (шаги взяты из инструкции к установке rbenv) - name: 'rbenv | clone repo' git: 'repo=git://github.com/sstephenson/rbenv.git dest={{ rbenv_root }} accept_hostkey=yes' - name: 'rbenv | check ruby-build installed' command: 'test -x {{ rbenv_root }}/plugins/ruby-build' # Мы проверяем, установлен ли ruby-build и регистрируем событие plugin_installed, # а затем выполняем все остальные шаги, которые не были изменены при следующем прогоне плейбука register: 'plugin_installed' ignore_errors: yes - name: 'rbenv | add bin to path' shell: echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> {{ home }}/.bashrc when: 'plugin_installed|failed' - name: 'rbenv | init' shell: echo 'eval "$(rbenv init -)"' >> {{ home }}/.bashrc when: 'plugin_installed|failed' - name: 'rbenv | clone ruby-build repo' git: 'repo=git://github.com/sstephenson/ruby-build.git dest={{ rbenv_root }}/plugins/ruby-build accept_hostkey=yes' when: 'plugin_installed|failed' - name: 'rbenv | check ruby {{ ruby_version }} installed' shell: 'RBENV_ROOT={{ rbenv_root }} PATH="$RBENV_ROOT/bin:$PATH" rbenv versions | grep {{ ruby_version }}' register: 'ruby_installed' ignore_errors: yes - name: 'rbenv | install ruby {{ ruby_version }}' shell: 'RBENV_ROOT={{ rbenv_root }} PATH="$RBENV_ROOT/bin:$PATH" rbenv install {{ ruby_version }}' when: 'ruby_installed|failed' - name: 'rbenv | set global ruby {{ ruby_version }}' shell: 'RBENV_ROOT={{ rbenv_root }} PATH="$RBENV_ROOT/bin:$PATH" rbenv global {{ ruby_version }}' when: 'ruby_installed|failed' - name: 'rbenv | rehash' shell: 'RBENV_ROOT={{ rbenv_root }} PATH="$RBENV_ROOT/bin:$PATH" rbenv rehash' when: 'ruby_installed|failed' - name: 'rbenv | create .gemrc' lineinfile: 'dest={{ home }}/.gemrc owner={{ user }} group={{ user }} mode=0644 line="gem: --no-ri --no-rdoc" create=yes' when: 'ruby_installed|failed' - name: 'ruby | install bundler' shell: 'RBENV_ROOT={{ rbenv_root }} PATH="$RBENV_ROOT/bin:$PATH" rbenv exec gem install bundler' when: 'ruby_installed|failed' - name: 'rbenv | change owner' shell: 'chown -R {{ user }}:{{ user }} {{ rbenv_root }}' when: 'ruby_installed|failed' # Устанавливаем posgresql, создаём пользователя, копируем конфиги и создаём конечную базу данных - name: 'postgresql | check user' shell: 'psql -U postgres -c "\copyright"' register: 'postgres_login' ignore_errors: yes - name: 'postgresql | set auth type' copy: 'src=configs/pg_hba.conf dest=/etc/postgresql/9.3/main/pg_hba.conf owner=postgres group=postgres mode=0644' when: 'postgres_login|failed' - name: 'postgresql | restart service' service: name=postgresql state=restarted when: 'postgres_login|failed' - name: 'postgresql | create shared directory' shell: 'mkdir -p {{ application }}/shared/config -m 775 && chown -R {{ user }}:{{ user }} {{ home }}/applications' when: 'postgres_login|failed' - name: 'postgresql | copy database.yml' # Модуль template позволяет нам не просто копировать файл из А в Б, но и переменные, которые будут автоматически подставляться внутри конфигов template: 'src=configs/database.yml dest={{ application }}/shared/config/database.yml owner={{ user }} group={{ user }} mode=0644' when: 'postgres_login|failed' - name: 'postgresql | create database' shell: 'createdb -U postgres -O postgres -E UTF8 -l en_US.UTF-8 {{ name }}_production' when: 'postgres_login|failed' # Rails setup | копируем settings.yml с нашими настройками - name: 'rails | copy settings.yml' copy: 'src=configs/settings.yml dest={{ application }}/shared/config/settings.yml owner={{ user }} group={{ user }} mode=0644' # Установка и настройка веб сервера nginx - name: 'nginx | check config' command: 'test -f /etc/nginx/sites-enabled/{{ name }}.conf' register: 'nginx_config_copied' ignore_errors: yes - name: 'nginx | createdir' shell: 'rm /etc/nginx/sites-enabled/default; mkdir -p etc/nginx/sites-enabled/' when: 'nginx_config_copied|failed' - name: 'nginx | copy config' template: 'src=configs/nginx.conf dest=/etc/nginx/sites-enabled/{{ name }}.conf owner=root group=root mode=0644' when: 'nginx_config_copied|failed' - name: 'nginx | restart service' # Модуль service - это ещё одна удобная обёртка, указываем какой сервис и что с ним необходимо сделать service: name=nginx state=restarted when: 'nginx_config_copied|failed' |
Mongoid doesn't save set value Posted: 03 Nov 2016 05:43 AM PDT My problem is that, with attributes that doesn't are set automatically, I'm receiving always nil value. Here are some examples: 2.3.1 :001 > t = Team.new(name: "team_1", code: "a123") => #<Team _id: 581b2f230640fd0cf4070a47, created_at: nil, updated_at: nil, code: nil, name: nil> 2.3.1 :002 > t.save => true 2.3.1 :003 > t => #<Team _id: 581b2f230640fd0cf4070a47, created_at: 2016-11-03 12:35:58 UTC, updated_at: 2016-11-03 12:35:58 UTC, code: nil, name: nil> 2.3.1 :004 > t.name = "team_1" => "team_1" 2.3.1 :005 > t => #<Team _id: 581b2f230640fd0cf4070a47, created_at: 2016-11-03 12:35:58 UTC, updated_at: 2016-11-03 12:35:58 UTC, code: nil, name: nil> Here is my model used in example: class Team include Mongoid::Document include Mongoid::Timestamps attr_accessor :name, :code, :owner_id, :learnin_object_ids, :active field :code, type: String field :name, type: String end My Gemfile: source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 5.0.0', '>= 5.0.0.1' # Use Puma as the app server gem 'puma', '~> 3.0' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.2' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.5' gem 'mongoid', '~> 6.0' gem 'bson_ext' gem 'moped' gem 'devise', '~> 4.0' group :development, :test do gem 'byebug', platform: :mri gem 'rspec-rails', '~> 3.0' gem 'factory_girl_rails', '~> 4.0' gem 'database_cleaner', '~> 1.0' end group :development do gem 'web-console' gem 'listen', '~> 3.0.5' gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' end gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] How can I save the right data? |
Rails show latest value after grouping Posted: 03 Nov 2016 05:26 AM PDT If I have this database table servers: date, server_id, server_name, server_status I have set in my controller: @servers = Server.all.group(:server_id) And assuming in my view I have a table like: <% @servers.each do |server| %> <td><%= server.server_name %></td> <td><%= server.server_status %></td> How do I show the server status at the most recent date recorded? |
Ruby- Mysql2 encoding utf8mb4 creating problems for indexing(affecting performance) Posted: 03 Nov 2016 05:33 AM PDT I am trying to create a composite index on my table because the below table is giving me performance issues and it has a character encoding of ut8mb4 and I am getting the following error Mysql2::Error: Specified key was too long The entire error is given below:- == 20161103114941 AddIndexOnKeyAndIdOnInvitees: migrating - Shard: master ===== -- add_index(:invitees, [:key, :created_at]) rake aborted! StandardError: An error has occurred, all later migrations canceled: Mysql2::Error: Specified key was too long; max key length is 767 bytes: CREATE INDEX `index_invitees_on_key_and_created_at` ON `invitees` (`key`, `created_at`) /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:299:in `query' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:299:in `block in execute' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract_adapter.rb:473:in `block in log' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/abstract_adapter.rb:15:in `instrument' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract_adapter.rb:467:in `log' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:299:in `execute' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/connection_adapters/mysql2_adapter.rb:231:in `execute' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:529:in `add_index' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:662:in `block in method_missing' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:632:in `block in say_with_time' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:632:in `say_with_time' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:652:in `method_missing' /var/www/production_hobnob_copy/db/migrate/20161103114941_add_index_on_key_and_id_on_invitees.rb:3:in `change' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:606:in `exec_migration' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:590:in `block (2 levels) in migrate' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:589:in `block in migrate' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:588:in `migrate' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:765:in `migrate' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:995:in `block in execute_migration_in_transaction' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:1043:in `ddl_transaction' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:994:in `execute_migration_in_transaction' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:956:in `block in migrate' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:952:in `each' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:952:in `migrate' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/migration.rb:86:in `migrate_with_octopus' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:820:in `up' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/migration.rb:113:in `block in up_with_octopus' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:246:in `block (2 levels) in run_queries_on_shard' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:509:in `using_shard' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:245:in `block in run_queries_on_shard' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:492:in `keeping_connection_proxy' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:244:in `run_queries_on_shard' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:253:in `block in send_queries_to_multiple_shards' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:252:in `map' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:252:in `send_queries_to_multiple_shards' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/migration.rb:112:in `up_with_octopus' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/migration.rb:798:in `migrate' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/migration.rb:104:in `block in migrate_with_octopus' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:246:in `block (2 levels) in run_queries_on_shard' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:509:in `using_shard' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:245:in `block in run_queries_on_shard' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:492:in `keeping_connection_proxy' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:244:in `run_queries_on_shard' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:253:in `block in send_queries_to_multiple_shards' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:252:in `map' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/proxy.rb:252:in `send_queries_to_multiple_shards' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/ar-octopus-0.8.6/lib/octopus/migration.rb:103:in `migrate_with_octopus' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/tasks/database_tasks.rb:137:in `migrate' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activerecord-4.2.1/lib/active_record/railties/databases.rake:44:in `block (2 levels) in <top (required)>' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/bin/ruby_executable_hooks:15:in `eval' /home/ubuntu/.rvm/gems/ruby-2.0.0-p648/bin/ruby_executable_hooks:15:in `<main>' Tasks: TOP => db:migrate I went through the following post in this forum:- Rails creating schema_migrations - Mysql2::Error: Specified key was too long and the solution given is to convert the character encoding to utf8 which is not possible in my case. Is there a work around for this. Any suggestions will be very helpful.. Thanks a lot |
Does rails' gem "composite_primary_keys" really alters db tables? Posted: 03 Nov 2016 05:07 AM PDT I'm newbie in Rails, so my appologies if this question looks stupid to you. Hello! I'm using Rails 5.0 with Postgresql. I'm in need to add composite primary keys to my model 'User_achievement' (to link 'User' and 'Achievement' models as you guess). So I tried using the "composite_primary_keys" gem. I followed all the instructions, nevertheless, the result wasn't like I expected. Seems like it doesn't create pkey in the 'user_achievement' table. Or maybe it shouldn't alter the table at all? It looks like I have to use 'execute' line with SQL code, but then what's the benefit in using the gem??? Here's the code: class CreateUsers < ActiveRecord::Migration[5.0] def change create_table :users do |t| t.string :name end end end class CreateAchievements < ActiveRecord::Migration[5.0] def change create_table :achievements do |t| t.string :ach_name t.text :ach_desc end end end class CreateUserAchievements < ActiveRecord::Migration[5.0] def change create_table :user_achievements, id: false do |t| t.belongs_to :user, :foreign_key => [:id] t.belongs_to :achievement, :foreign_key => [:id] t.date :uach_date end end end class Achievement < ApplicationRecord has_many :user_achievements end class User < ApplicationRecord has_many :user_achievements end class UserAchievement < ApplicationRecord self.primary_keys = :user_id, :achievement_id belongs_to :user, :foreign_key => [:id] belongs_to :achievement, :foreign_key => [:id] end When I use psql it shows references to 'users' and 'achievements' as it has to be, but there's no info about pkey at all! I'm thankful for your help! |
How do easily filter CSV data in Ruby Posted: 03 Nov 2016 06:57 AM PDT I am dealing with a CSV file(approx 500 lines). Is there a way to select data from this file with filters. I know I can do this in ruby by parsing the csv and using select/find methods But I am looking for a simpler syntax. I don't want to write methods to process each of the below queries. Any gem that would allow me do these queries? I am looking for a non-Rails solution as I am writing a plain ruby script. e.g. csv.find_rows(where: {'GENDER' => 'MALE'}.count or csv.find_rows(where: {'GENDER' => 'MALE', 'SALARY' >= 10000 } |
Rspec mock return value of multiple dimensions array Posted: 03 Nov 2016 06:01 AM PDT I need to mock a return value from a specific inner key in my array. I want to mock this: CONFIG['key1']['key2'] I thought of doing something like this: allow(CONFIG).to receive(:[], :[]).with('key1', 'key2').and_return(['my mock']) but this is not the right way to write it. Does anyone knows how it should be written? Thanks! |
Couldnot access the controller method from javascript in rails Posted: 03 Nov 2016 04:43 AM PDT I am having a scenario where Forgot password is displayed in a Modal when click on link from sessions -> new / signin form. Now I need to add validation for "check if email exists". For this I added a route, method in users_controller, script in sessions/new as shown below. With alerts and rails log I came to know that, when I click on button it is not going to users_controller/ checkemail method and every email is showing as "Email doesnot exists". Please help me what the mistake I have done? routes.rb: devise_for :users, :controllers => {:sessions => 'sessions'}, :path => '', :path_names => { :sign_in => "login", :sign_out => "logout" } get "/checkemail" => "users#checkemail", as: :checkemail users_controller.rb: def checkemail puts "****************************************" @checkemail = User.find_by_email(params[:checkemail]) if @checkemail.present? respond_to do |format| format.json { render json: "0" } end else respond_to do |format| format.json { render json: "1" } end end end app/views/sessions/new.html.erb: <%= semantic_form_for(resource_name, :url => password_path(resource_name), :remote => true, :format => :json, :html => { :id => 'password_reset' }) do |f| %> <input type="hidden" id="email_flag" value="0"> <%= f.inputs do %> <%= f.input :email, :label => 'Your email address', :input_html => { :id => 'user_email_field',:placeholder => "Enter your email..."}%> <label id="error_explanation1" class="error errorExplanation" style="margin-top:-10px;"></label> <% end %> <%= f.buttons do %> <%= f.commit_button :label => 'Send me that link', :button_html => {:class => 'submit button', :id => 'forgot_password_button', :disable_with => 'Wait...' }%> <% end %> <% end %> <script type="text/javascript"> $( "#forgot_password_button" ).click(function(e) { var userEmail = $("#user_email_field").val(); var v1 = validateFirstPage(); if(v1){ return true; }else{ return false; } }); $( document ).ready(function() { $( document ).on( "change", "#user_email_field", function() { var email = $("#user_email_field").val(); var url = "/checkemail?checkemail="+email; $.get( url, function( data ) { $("#email_flag").val($.trim(data)); }); }); }); function validateFirstPage(){ var email_flag = $.trim($("#email_flag").val()); var userEmail = $.trim($("#user_email_field").val()); if(email_flag =="1"){ $("#error_explanation1").html("").fadeOut(); }else{ if(userEmail != "" && email_flag !="1"){ var error_msg = "Email doesnot exists"; $("#error_explanation1").html(error_msg).fadeIn(); } else{ $("#error_explanation1").html("").fadeOut(); } return false; } } </script> |
Redirecting in before_filter and go on with original request Posted: 03 Nov 2016 07:43 AM PDT In my app I use OAuth to authenticate in other sources, so that I need to keep their tokens for each user. I store tokens in entities I call openids . In that way, I want to check if openid is valid (token is not expired) before creating and updating some models' objects. If token is expired, I want to redirect user to logging in and then go on with the action that was interrupted by login (creating, updating, etc). My idea was to save request.fullpath in cookies and then, when the authorization is over, in the method that called when callback of login method initiated, redirect user to previous action by using redirect_to cookies[:auth_back_path] . The thing is for example, update method needs PATCH request to be called. redirect_to provides only GET methods. So that in one of the controllers I have (ones_controller.rb ): before_filter :check_openids, except: [:relogin, :show] .... def check_openids unless current_user.openid_actual? cookies[:auth_back_path] = request.fullpath redirect_to '/auth' end end Can, please anyone tell, how can I make it in a right way? I really want to realise how it all's going. P.S.: I read here that force doing patch or delete (when I will call destroy method) is not a good idea. |
Rails: update multiple records single column value while the records were retrieved using a group by clause Posted: 03 Nov 2016 06:12 AM PDT I am retrieving some data from a table using a group by clause and after that I want to update a single column value for all the records which were retrieved by the initial query. So I need to make sure that since the initial query until I update the records no new line were added. Explanation: So lets say the model Test has 5 columns: Id A B C Status So first I query as follows: Test.select('count(*), A, B').where(status:'new', C: 'value').group('A, B') After I process the groups in code I want to change the status of all the records that were used by the initial query to done Problem is that if I just do: Test.where(status: 'new', C: 'value') In order to now use update_all there is chance new records were added to the table since the first query that answer this condition and I will set their status to 'Done' although they weren't really processed because during the initial query they didn't exist. So basically I need a way to either lock the table from insertions since the initial query until the update OR in some way get a list of the id's that were "considered" in the group by query. How do I do that? |
ActiveAdmin unpermitted param on has many: through association Posted: 03 Nov 2016 07:25 AM PDT I went through around 12 StackOverflow questions similar to this one but none of them seem to help me out. Active admin: Article.rb permit_params tag_ids: [] ... f.input :tag, as: :check_boxes, collection: Tag.all.map { |h| [h.name, h.id] } Tag: class Tag < ApplicationRecord has_many :taggings has_many :articles, through: :taggings Taggings: class Tagging < ApplicationRecord belongs_to :article belongs_to :tag end Article: class Article < ApplicationRecord belongs_to :category has_many :taggings has_many :tags, through: :taggings I tried permitting the following: - tag_ids:[]
- tag_ids: [:id]
- tag_attributes: [:id]
Getting: found unpermitted parameter: hashtag Something is missing! UPD 1 Here's my log: [INFO ] === Processing by Admin::ArticlesController#update as HTML [INFO ] Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "article"=>{"tag"=>["", "1", "2"] ...}, "commit"=>"Update Article", "id"=>"1"} [DEBUG] AdminUser Load (2.1ms) SELECT "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = $1 ORDER BY "admin_users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]] [DEBUG] Article Load (0.4ms) SELECT "articles".* FROM "articles" WHERE "articles"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]] [DEBUG] Unpermitted parameter: tag |
how can i creating mail Threads using ruby during send mail Posted: 03 Nov 2016 03:57 AM PDT I am trying to implement mail Thread (Conversation threading)in one of my application (client mail). I want to conversion of two more user with same subject that should be in the same mail conversation.and its shows in same group. I am also want to do it with out using Gmail Client Api. How can i improve in ruby on rails application? |
No comments:
Post a Comment