Rails uniqueness validation failing Posted: 14 Jul 2016 07:57 AM PDT I have a SapEvento model which belongs to SapIntegracao model. On SapEvento, I have the following validation: validates :params_operacao, uniqueness: true, if: :check_params def check_params self.sap_integracao_log.recebimento end I'm doing that to prevent duplicate requests on a soap integration (sometimes the same xml comes multiple times). So the params I receive are saved on that :params_operacao attribute, as a string. But the problem is the validation in saving. When I receive the XML and create the SapEvento object by doing evento_erro = sap_integracao_log.sap_eventos.create( evento_tipo: SapEvento.get_evento_tipo("Erro na Integração"), params_operacao: params.to_s, erro_descricao: (!transporte ? "Transporte não encontrado" : erro), reenviado: false, operacao: operacao ) it doesn't validate and permits to create another object, even if already exists an object with same :params_operacao value. I debugged on check_params method: logger.debug "recebimento #{self.sap_integracao_log.recebimento}" logger.debug "count #{SapEvento.where(params_operacao: self.params_operacao).count}" and recebimento is true and the count is bigger than 0... so it shouldn't permitt, right? I also tried some other syntaxes, like: validates :params_operacao, uniqueness: true, if: "self.sap_integracao_log.recebimento" but none of these worked. Any ideas? |
What is the reason for the nil entry in Rails localisation month and day arrays? Posted: 14 Jul 2016 08:02 AM PDT I am using Rails i18n and I noticed that for months a nil must be entered (as mentioned in the documentation here: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15_) like this: month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December] as there is no such thing as a 0th month. Why is this important, why isn't January just returned for the first element? How does this work? |
Order by Nearest using PostGIS, RGeo, Spatial Adapter Posted: 14 Jul 2016 07:58 AM PDT I'm asking this question because the answers I've found in Order by nearest - PostGIS, GeoRuby, spatial_adapter wasn't able to provide a solution. I'm trying to create a controller method that can return the n closest records to a certain record's lonlat. The record it is querying against is from the same table. This concept isn't such a big stretch if I was doing this completely in SQL. That much is clear in the linked example and below is a specific case where I obtained a result: condos_development=# SELECT id, name FROM condos ORDER BY ST_Distance(condos.lonlat, ST_PointFromText('POINT(-71.06 42.45)')) condos_development-# LIMIT 5; My problem is in making this work with ActiveRecord. I'm using a method that was inspired by the response by @dc10 but I'm unable to create a working query either through the RGeo methods, or direct SQL. Here's what I have so far: def find_closest_condos(num, unit) result = Condo.order('ST_Distance(condos.lonlat, ST_PointFromText("#{unit.lonlat.as_text)}")').limit(5) end The response from this attempt is as follows: ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "LIMIT" 10:29:50 rails.1 LINE 1: ...lonlat, ST_PointFromText("#{unit.lonlat.as_text)}") LIMIT $1 Would someone be able to set me on the right track on how to put this work query together so that I can make it work in Rails? |
Rails SCSS Background Image Not Rendering Posted: 14 Jul 2016 08:03 AM PDT I have a background image I'm putting on a div that is not loading to the page even though the path checks out. Here is what the inspector looks like: when I move my mouse over the path to see the image, on hover instead of seeing the image like normal the browser shows the path: localhost:8080/app/public/app/assets/images/backgrounds/person-blur.png does this mean the image is not loading correctly? My page renders fine with no errors in the console, so why wont this image show? strangely enough when i do a background-color: red on the same property it shows up just fine... |
Routing error in edit method Posted: 14 Jul 2016 07:41 AM PDT I'm writing a little Rails CMS and I'm a little stuck with a routing error. To begin with, I have a basic model called Entry , which other models are inheriting from. When I try to edit an existing model, it returns me an error No route matches [PATCH] "/admin/posts/entries" In my routes.rb in CMS plugin I have the following: Multiflora::Engine.routes.draw do root "dashboard#index" scope "/:content_class" do resources :entries end end and in test app's routes.rb I have mount Multiflora::Engine, at: '/admin' In application_controller.rb I also tweaked routes a little: def content_entries_path entries_path(content_class: content_class.tableize) end helper_method :content_entries_path def content_entry_path(entry) entry_path(entry, content_class: content_class.tableize) end helper_method :content_entry_path def new_content_entry_path new_entry_path(content_class: content_class.tableize) end helper_method :new_content_entry_path def edit_content_entry_path(entry) edit_entry_path(entry, content_class: content_class.tableize) end helper_method :edit_content_entry_path And in my show.html.erb I have this: <%= link_to 'Edit', edit_content_entry_path(@entry) %> When I navigate to edit_content_entry_path , it shows me edit page correctly, but when I try to save edited entry, it returns me an error stated above. When I run rake routes , it returns me the following: entries GET /:content_class/entries(.:format) multiflora/entries#index POST /:content_class/entries(.:format) multiflora/entries#create new_entry GET /:content_class/entries/new(.:format) multiflora/entries#new edit_entry GET /:content_class/entries/:id/edit(.:format) multiflora/entries#edit entry GET /:content_class/entries/:id(.:format) multiflora/entries#show PATCH /:content_class/entries/:id(.:format) multiflora/entries#update PUT /:content_class/entries/:id(.:format) multiflora/entries#update DELETE /:content_class/entries/:id(.:format) multiflora/entries#destroy |
Translating High Resolution Adobe Creative SDK from PHP to Ruby on Rails Posted: 14 Jul 2016 07:42 AM PDT I am trying to implement Adobe's Creative SDK into my Ruby on Rails app. https://creativesdk.adobe.com/docs/web/#/articles/highresolution/index.html I have the required access to the hi-res API. The examples they have are for PHP and Node.js, and I am trying to write a Ruby on Rails version based on the PHP. I have it all setup, in that it's properly calling the "authenticationURL" but I'm getting an "Invalid authenticationURL response. Please check the formatting the response." I'm new to programming at this level and basically tried to figure this out by referencing a few questions on PHP & Ruby here as well sites like http://www.phptoruby.com/. Here is the PHP: <!-- /getAuth --> <?php $apiKey = "apikey"; $apiSecret = "apisecret"; $salt = rand(0,1000); $time = time(); $sig = sha1($apiKey . $apiSecret . $time . $salt); $authObj = array( "apiKey" => $apiKey, "salt" => $salt, "timestamp" => $time, "encryptionMethod" => 'sha1', "signature" => $sig ); echo json_encode($authObj); ?> Here is what I have at the moment (with my apikey and apisecret entered correctly): require 'time' require 'json' require 'digest/sha1' def get_auth apiKey = 'apikey' apiSecret = 'apisecret' salt = "#{0 + rand(1000)}" time = "#{Time.now.to_i}" sig = Digest::SHA1.hexdigest('apiKey' + 'apiSecret' + 'time' + 'salt') authObj = { :apiKey => 'apiKey', :salt => 'salt', :timestamp => 'time', :encryptionMethod => 'sha1', :signature => 'sig' } print 'authObj'.to_json render :fxb end I'm not sure if using print is correct here? Or if my problem is a syntax issue... Or something else entirely. |
Integrate Ruby-Lint with Rspec Posted: 14 Jul 2016 07:27 AM PDT I have project with Bunlder and Rspec (actually it is Rails 4.2 app) I want ruby-lint to correctly works with my specs. By default it doesn't: $ ruby-lint spec/models/user_spec.rb user_spec.rb: error: line 3, column 1: undefined constant RSpec user_spec.rb: error: line 4, column 3: undefined method describe user_spec.rb: error: line 5, column 5: undefined method let I have require 'rails_helper' in spec/models/user_spec.rb so It is natural to expect that ruby-lint would load it and therefore load rspec . What should I do in order to make ruby-lint to handle spec files correctly? P.S. I don't have any specific ruby-lint configuration. |
Ruby on Rails vs Django/Python, main technical advantages/disadvantages? [on hold] Posted: 14 Jul 2016 07:33 AM PDT I have been designing web applications for over two years now, solely using C# web services along with AngularJs MVC framework. Lately I've been doing some research into other Web programming languages such as Ruby on Rails and Django/Python (from what I found, PHP seemed to be the worst in terms of usability and functionality), however I would like to know what are some advantages and disadvantages stack-overflow members have been facing lately. This is not opinion based. I want to know what are the main technical advantages and disadvantages of each framework. Thanks in advance for the help. |
Rails range slider output Posted: 14 Jul 2016 07:17 AM PDT With simpleform I was able to create a slider vor an input, but I want the value to be visible, like in this example Here is the codesnippet from my application. = f.input :numberone, as: :range, input_html: { min: '1', max: '4', step: '1'} How can I add such an "output"? |
Ruby on Rails - Find Last round when using each_slice Posted: 14 Jul 2016 07:16 AM PDT I am using each_slice in my application to show a ad code every 4 image. This is how i am doing it: - @post.images.each_slice(4) do |group| - group.each do |image| // My images %div.ads // My ads code How can I find the last round and prevent it to show ad since I don't want to show ad on last round. I have done what it says here, But no luck: How to know that we're on "the last round" of a .each_slice I added the last_slide method in my post_controller and get wrong number of arguments when I run/before_action it in my show -view and when I don't run in my controller, nothing happens. |
How to develop Rails app running inside Docker Posted: 14 Jul 2016 06:56 AM PDT guys. I have the legacy Rails application running in Docker container. There are Docker images inside container. Everything works fine. But I see significant problem. Every time I change the application code (controllers, models and so on) and want to changes get reflected to my browser I need to do docker-compose up . This is so convenient. So the question is how to develop/debug the Rails app running in Docker without reloading Docker? Thanks. |
Polymorphic Table for comments in Rails Posted: 14 Jul 2016 07:47 AM PDT I am building out an app where multiple objects will have comments. I originally designed the app where the only thing that could have comments were Posts, but since have changed directions to make comments polymporphic. Here is my Post model class Post < ActiveRecord::Base include Bootsy::Container belongs_to :user belongs_to :post_category has_many :comments, as: :commentable validates_presence_of :post_category, :user scope :sticky, -> { where sticky: true } scope :not_sticky, -> { where sticky: false } scope :for_category, ->(cat_id) { where post_category_id: cat_id } def is_new? created_at > Time.now - 24.hours end end Comments Model class Comment < ActiveRecord::Base include Bootsy::Container belongs_to :commentable, polymorphic: true belongs_to :user end Currently, Posts (posts in a forum) are namespaced and for my other commentable objects, they won't be namespaced. Should I have a CommentsController in the namespaced forum controllers directory and a CommentsController in the main controllers directory? My routes look like this (so far): # Recently added resources :comments, only: [:create] namespace :forum do resources :posts, only: [:index] do resources :comments, only: [:create] end resources :post_categories, only: [:index] do resources :posts, only: [:index, :show, :new, :create, :edit, :update] end end |
rspec raise error if configuration not given by gem user Posted: 14 Jul 2016 06:45 AM PDT I am working on a gem in which configurations are given as follows configuration.rb file module ModuleName class Configuration attr_accessor :attr1, :attr2, :attr2 def initialize @attr1 = '' @attr2 = '' @attr3 = '' end end end my configuration setters are module ModuleName class << self attr_accessor :configuration end def self.configure self.configuration = Configuration.new yield(configuration) end end now i have the functionality that if a user don't set configuration in his rails app, he will get an error. Problem i am facing is that, how do i raise that error if configurations are missing. i tried to use rescue NoMethodError but that resulted in failure for many test cases. Can anyone tell me how i can achieve this functionality so that if a user doesn't set configuration in app, he will get error that configurations are missing . Also my specs won't fail. |
Inline error messages in a form_for with remote: true Posted: 14 Jul 2016 07:03 AM PDT I have a form in a modal that looks like this: <%= form_for (@change_office_address_), remote: true, format: :json, html: { class: :contact_form } do |f| %> <div id="error_explanation" style='display:none;' class="bg-danger text-danger alert fade in alert-danger alert-dismissable errors"> <ul> <% if @change_office_address_.errors.any? %> <% @change_office_address_.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> <% end %> </ul> </div> <%= f.hidden_field :city_id, value: @office.city.id %> <%= f.hidden_field :office_id, value: @office.id %> <%= f.hidden_field :insurer_id, value: @office.insurer.id %> <%= f.text_field :name, placeholder: 'Name', class: 'form-control' %> <br> <%= f.text_field :email, placeholder: 'e-mail', class: 'form-control' %> <br> <%= f.label :city_name, 'City' %> <%= f.text_field :city_name, class: 'form-control', value: @office.city.name.mb_chars.titleize, readonly: true %> <br> <%= f.label :insurer_name, 'Insurer' %> <%= f.text_field :insurer_name, class: 'form-control', value: @office.insurer.short_name, readonly: true %> <br> <%= f.label :office_name, 'Insurer\'s office address' %> <%= f.text_field :office_name, class: 'form-control', value: @office.address, readonly: true %> <br> <%= f.text_field :edit_office_address, placeholder: 'New address', class: 'form-control' %> <br> <%= f.text_area :comment, placeholder: 'Comment', class: 'form-control', cols: '30', rows: '5' %> <br> <div class="text-center"> <%= f.submit 'Inform about deleting', class: 'btn btn-danger' %> <%= f.submit 'Inform about changing address', class: 'btn btn-default' %> </div> <% end %> After the form was submitted, and validations didn't pass, I can see error messages at the top of my form. But I'd like to show errors inline. I tried to add <span class="help-inline"><%= @change_office_address_.errors[:email] %></span> into my form, but it doesn't work. A controller: class ChangeOfficeAddressesController < ApplicationController def create @change_office_address = ChangeOfficeAddress.new(change_office_addresses_params) respond_to do |format| if params[:commit] == 'Inform about changing address' if @change_office_address.save format.html { ChangeOfficeAddressMailer.change_office_address_new(@change_office_addres).deliver_now redirect_to :back, notice: 'Thanks.' } format.json { redirect_to :back, status: :created, location: @change_office_address, notice: Thanks.' } else format.json { render json: @change_office_address.errors.full_messages, status: :unprocessable_entity } end elsif params[:commit] == 'Inform about changing address' @change_office_address.delete_office_address = 'Some text' @change_office_address.edit_office_address = nil if @change_office_address.save format.html { ChangeOfficeAddressMailer.change_office_address_new(@change_office_addres).deliver_now redirect_to :back, notice: 'Thanks.' } format.json { redirect_to :back, status: :created, location: @change_office_address, notice: 'Thanks.' } else format.json { render json: @change_office_address.errors.full_messages, status: :unprocessable_entity } end else if @change_office_address.save format.html { ChangeOfficeAddressMailer.change_office_address_new(@change_office_addres).deliver_now redirect_to :back, notice: 'Thanks.' } format.json { redirect_to :back, status: :created, location: @change_office_address, notice: 'Thanks.' } else format.json { render json: @change_office_address.errors.full_messages, status: :unprocessable_entity } end end end end private def change_office_addresses_params params.require(:change_office_address).permit(:email, :name, :edit_office_address, :add_office_address, :delete_office_address, :office_id, :insurer_id, :city_id, :comment) end end And application.js: $(document).ready(function() { return $(document).bind("ajaxError", "form.contact_form", function(event, jqxhr) { var $contact_form, $error_container, $error_container_ul; $contact_form = $(event.data); $error_container = $("#error_explanation", $contact_form); $error_container_ul = $("ul", $error_container).empty(); if ($error_container.is(":hidden")) { $error_container.show(); } else { $("#error_explanation").remove("#error_explanation"); } return $.each(jqxhr.responseJSON, function(index, message) { return $("<li>").html(message).appendTo($error_container_ul); }); }); }); Is there any way to add those error messages? Thanks. |
Rails incorrect date query Posted: 14 Jul 2016 06:52 AM PDT I have problem with ActiveRecord queries. I suppose that it connected with Time Zone. This is example date_start = Date.parse(params[:filter][:date_start]).beginning_of_day date_end = Date.parse(params[:filter][:date_start]).end_of_day data = MyModel.where("created_at>=? and created_at <=?", date_start, date_end) If params are params[:filter][:date_start] is "10.07.16" and params[:filter][:date_end] is "15.07.16" Dates in resulting query will be incorrect. The resulting dates will be [correct date] - [zone time diff]. So insted of 2016-07-16 00:00 for start_end I have 2016-07-15 21:00 |
create node attribute/return value in custom resource for chef Posted: 14 Jul 2016 06:36 AM PDT I have a chef resource that needs to return a version. I looked up and fund the best way to publish it as a node attribute. Here is the resource code(dj_artifactory_version) : require "open-uri" require "json" def whyrun_supported? true end def get_version(name, user, pass, type, organization, art_module, repos, version) if (type.match(/snapshot$/i) and version.match(/latest$/i)) string_object = open("https://artifactory.io/artifactory/api/search/versions?g=#{organization}&v=*.*.*&a=#{art_module}&repos=#{repos}", :http_basic_authentication=>["#{user}", "#{pass}"], :ssl_verify_mode=>OpenSSL::SSL::VERIFY_NONE) json_file = JSON.parse(string_object.read) version_array = Array.new json_file["results"].each do |version| version_array.push(version["version"]) end unique_versions=(version_array.uniq).max node.set['artifact']['snapshot']['latest'] = unique_versions Now I use this chef resource in my recipe to get the version : dj_artifactory_version "test" do type "snapshot" # options - snapshot/release organization "djcm.billing.api.admin" # layout.organization in artifactory properties. modules "paypal" # layout.properties in artifactory properties. repos "djcm-zip-local" # repository name in artifactory version "latest" #latest/oldest end p "#node{['artifact']['snapshot']['latest']}" I create default['artifact']['snapshot']['latest'] in default.rb with a value but here even after I run my recipe the old value doesn't change. Interestingly when I print the same in my resource, it print the node with the new value. What am I doing wrong and is there a better way to publish a value using your own resource ? |
Unable to fetch MySQL data on Ruby on Rails using capybara Posted: 14 Jul 2016 06:20 AM PDT I have a file called test_spec.rb inside my spec/features folder. It runs good when I type rake spec But it doesn't load any data from the database. I have put some database in test and development environment in Database.yml So both database are same, I got only one database, i.e. app_development. I want that the select query should be able to fetch MySQL data inside the test_spec.rb. |
Rails form_for form sending nil without letting displaying the view Posted: 14 Jul 2016 07:54 AM PDT This must be a beginner thing that I am overlooking, but I have a form in a rails 4.2.1 app made with form_for. My problem is that I am not able to actually SEE the form, it won't display whatsoever. Worse yet, rather than seeing the page view, it simply passes nil through to the method and gives me errors because my methods obviously don't work for nil. I have tried playing around with the routes file to no avail, is there something simple that I'm missing that would just cause a form to behave in this way? I've consulted the official guides and the hartl tutorial, but I've got nothing. EDIT: My controller for product is below: class ProductsController < ApplicationController def new @product = Product.new end def create @product = Product.new(product_params) end def show @product = Product.find(params[:code]) end def ship @product = Product.find_by(code: params[:code]) @product.quantity -= 1 if @product.save respond_to do |format| format.html {} format.json{} end end end private def product_params params.require(:product).permit(:code, :product, :quantity) end end and my view for the ship method is below: <%= form_for(@product) do |f| %> <%= f.label :code %> <%= f.text_field :code %> <%= f.submit "Submit", class: "btn btn-primary" %> <% end %> I would be so grateful for any help. I've been staring at this for so long and there has to be something I'm missing. |
Calling methods in other models in controller Posted: 14 Jul 2016 06:55 AM PDT So, I'm pretty new to the concept of offloading functionality that affects the DB into a model instead of a controller and having some difficulty getting it to work. Basically, from my Stock controller, I'm trying to call a method in my User model. Instead, I'm getting an error: NoMethodError (undefined method `stock_relationships' for #<Class:0x007fc0da1a8d60>): app/models/user.rb:27:in `follow_stock' app/controllers/stocks_controller.rb:20:in `add_stock' So, here is what I have: A user adds a stock in views/stocks/index.html.erb <% @stocks.each do |s| %> <tr> <td><%= s.symbol %></td> <td><%= s.name %></td> <td> <%= link_to raw("<i class='fa fa-plus'></i>"), add_stock_path(id: s.id) %> </td> </tr> <% end %> Which then triggers the StockController add_stock method: def add_stock stock = Stock.find(params[:id]) user = current_user.id User.follow_stock(stock_id: stock, user_id: user) flash[:success] = "Successfully added stock" redirect :back end The 3rd line in the method is where my problem is, since the follow_stock method resides in the User model: class User < ActiveRecord::Base has_many :stock_relationships has_many :stocks, through: :stock_relationships def self.follow_stock(stock) self.stock_relationships.create(stock_id: stock) end end Can some one help me wrap my head around how to actually call this method or am I totally off base with how I'm trying it? UPDATE I've changed some code around and now I am able to create the StockRelationship however, stock_id is being saved as nil : => #<StockRelationship:0x007fee03f25f00 id: 17, user_id: 1, stock_id: nil, created_at: Thu, 14 Jul 2016 13:44:52 UTC +00:00, updated_at: Thu, 14 Jul 2016 13:44:52 UTC +00:00> I changed the code in StockController#add_stock : def add_stock stock = Stock.find(params[:id]) current_user.follow_stock(stock) flash[:success] = "Successfully added stock" redirect_to :back end |
Why use Ember.js with Rails? Posted: 14 Jul 2016 07:08 AM PDT I have been wondering for some time why should I use Ember in combination with Rails? RoR has templating system, Ember has one. They both have: - models
- views
- partials
- etc.
Can anyone explain to me why should I use them in a combination? |
how can i connect to microsoft access database from rails application? [duplicate] Posted: 14 Jul 2016 06:03 AM PDT This question already has an answer here: I want to connect to microsoft access database from my rails application. I have rails application which is running on the linux platform , and the database of my rails application is My Sql . i have some data in microsoft access database, this access database server is running on the windows operating system . my requirement is connecting my rails application which is running on linux os to the microsoft access database that runs on windows os . and after connecting, i will do some coding to save the data in my mysql database of rails . Previously, I have sucessfully connected to microsoft sequel server database from my rails application and successfully saved data in my mysql database. with the following logic, by using tiny tds gem and native sql query . client = TinyTds::Client.new username: user_name, password: password, dataserver: db_ip_addr ,database: db_name result = client.execute("select * from DeviceLogs WHERE LogDate >= '#{date1}' AND LogDate < '#{date2}' AND UserId = #{employee.biometric_id} ORDER BY LogDate ASC ;") is there any similar kind of Approach to connect to microsoft access database? is there any gem through which i can do this? |
bad uri is not uri error on proxy Posted: 14 Jul 2016 05:57 AM PDT i'm trying to connect to a webpage like this doc = Nokogiri::HTML(open(url, :proxy => "198.50.142.47:3128")) However i get this error URI::InvalidURIError (bad URI(is not URI?): 198.50.142.47:3128): Any ideas how to fix this? |
nested form params blank? problems Posted: 14 Jul 2016 07:30 AM PDT dear fellow programmers, I am having a little problem with my nested form within another form.. here is what i'm trying to do, this current form is to add owners to current_customer. But within this form has a nested form to input owner's telephone number into the telephones table which is separated from the owners table -- hence the nested form. Users have to enter their owners name to create a new owner, but telephone number can be added later. The said form is as follows: <%= form_for(@owner) do |f| %> <%= f.hidden_field :customer_id, :value => params[:id] %> <%= f.label :name %> <%= f.text_field :name, class: 'form-control' %> <%= f.label :email %> <%= f.email_field :email, class: 'form-control' %> <%= f.fields_for :telephones do |t| %> <div class="form-group"> <%= t.hidden_field :owner_id, :value => @owner.id %> <div class="number-type"> <%= t.label :tel, "Contact number" %> <%= t.radio_button :numbertype, "mobile", :checked => false, :class => "numbertype mobile" %> <%= t.label :numbertype, "Mobile", :value => "mobile" %> <%= t.radio_button :numbertype, "land", :class => "numbertype land" %> <%= t.label :numbertype, "Land", :value => "land" %> </div> <%= t.text_field :number, placeholder: "telephone number", class: 'form-control some_input' %> <%= t.text_field :ext, placeholder: "extension", id: "extension", class: 'form-control'%> </div> <% end %> <%= f.submit "Add new owner", class: "btn btn-primary" %> The telephone.rb model is as follows: class Telephone < ActiveRecord::Base belongs_to :customer belongs_to :owner validates :owner_id, presence: true, allow_blank: true validates :customer_id, presence: true, allow_blank: true validates :numbertype, presence: true, allow_blank: true validates :number, presence: true, allow_blank: true, length: { in: 7..10 }, uniqueness: { scope: [:ext] }, :numericality => {:only_integer => true} validates :ext, presence: true, allow_blank: true end owners_controller.rb def create @customer = Customer.find(params[:owner][:customer_id]) @owner = Owner.find_by(customer_id: params[:id]) if number_blank? @owner = @customer.owners.build(owner_params) else @owner = @customer.owners.build(owner_with_telephone_params) end if @owner.save @customer.update_attribute(:updated_at, Time.zone.now) flash[:success] = "New owner added!" redirect_to request.referrer else flash[:danger] = "no owner has been added." redirect_to @customer end end private def owner_with_telephone_params params.require(:owner).permit(:name, :email, :tel, telephones_attributes: [:numbertype, :number, :ext]) end def owner_params params.require(:owner).permit(:name, :email, :tel) end def number_blank? params[:owner][:telephones_attributes][:number].blank? end the problem i am facing with my code is that even my :number field in this form is filled, the number cannot be entered into the telephone table. Is it as if rails could not detect my :number field is blank? or not. if there something that i am doing wrong? much appreciate your help! |
Rails FactoryGirl instance variable Posted: 14 Jul 2016 08:06 AM PDT I would like to create factory using local variable. Currently I have the following factory: FactoryGirl.define do factory :offer_item, class: BackOffice::OfferItem do service variant end end My expectation is to create something like below FactoryGirl.define do variant = FactroyGirl.create(:variant) factory :offer_item, class: BackOffice::OfferItem do service variant { variant } after(:create) do |offer_item| offer_item.service.variants << variant end end end but then I get: /.rvm/gems/ruby-2.2.3/gems/factory_girl-4.7.0/lib/factory_girl/registry.rb:24:in `find': Factory not registered: variant (ArgumentError) All models are nested inside BackOffice module. Generally I want the same object has association with two other objects. I think there is a some problem with scope in my factory. Variant factory is inside other separated file. |
Heroku H10 Error-- Git was initialized in parent directory (not in app directory) Posted: 14 Jul 2016 05:39 AM PDT I'm deploying my Rails app to Heroku for the first time and getting an H10 error. I believe it's because I initially initialized my git repo inside a parent directory that contained some other folders, and one of the folders is my actual app content, titled app_name. I think this is causing errors with Heroku, and I'm not sure how to debug. None of the usual suspects helped with the app crashing presumably because my situation isn't so common: I ran heroku run rails console, and had the following output whether I was in the parent directory or the app dir: Usage: rails new APP_PATH [options] Options: -r, [--ruby=PATH] # Path to the Ruby binary of your choice # Default: /app/vendor/ruby-2.2.4/bin/ruby -m, [--template=TEMPLATE] # Path to some application template (can be a filesystem path or URL) [--skip-gemfile], [--no-skip-gemfile] # Don't create a Gemfile -B, [--skip-bundle], [--no-skip-bundle] # Don't run bundle install -G, [--skip-git], [--no-skip-git] # Skip .gitignore file [--skip-keeps], [--no-skip-keeps] # Skip source control .keep files -O, [--skip-active-record], [--no-skip-active-record] # Skip Active Record files -S, [--skip-sprockets], [--no-skip-sprockets] # Skip Sprockets files [--skip-spring], [--no-skip-spring] # Don't install Spring application preloader -d, [--database=DATABASE] # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc) # Default: sqlite3 -j, [--javascript=JAVASCRIPT] # Preconfigure for selected JavaScript library # Default: jquery -J, [--skip-javascript], [--no-skip-javascript] # Skip JavaScript files [--dev], [--no-dev] # Setup the application with Gemfile pointing to your Rails checkout [--edge], [--no-edge] # Setup the application with Gemfile pointing to Rails repository [--skip-turbolinks], [--no-skip-turbolinks] # Skip turbolinks gem -T, [--skip-test-unit], [--no-skip-test-unit] # Skip Test::Unit files [--rc=RC] # Path to file containing extra configuration options for rails command [--no-rc], [--no-no-rc] # Skip loading of extra configuration options from .railsrc file Runtime options: -f, [--force] # Overwrite files that already exist -p, [--pretend], [--no-pretend] # Run but do not make any changes -q, [--quiet], [--no-quiet] # Suppress status output -s, [--skip], [--no-skip] # Skip files that already exist Rails options: -h, [--help], [--no-help] # Show this help message and quit -v, [--version], [--no-version] # Show Rails version number and quit Description: The 'rails new' command creates a new Rails application with a default directory structure and configuration at the path you specify. You can specify extra command-line arguments to be used every time 'rails new' runs in the .railsrc configuration file in your home directory. Note that the arguments specified in the .railsrc file don't affect the defaults values shown above in this help message. Example: rails new ~/Code/Ruby/weblog This generates a skeletal Rails installation in ~/Code/Ruby/weblog. See the README in the newly created application to get going. I also ran heroku restart which just returned "..done" on both directories of interest. Something unusual I'd like to point out-- because I initialized my git repo in my parent directory, I had to throw in copies of my gem file in the parent directory as well in order for heroku buildpack to compile properly. Also, interestingly enough, if I run heroku run rake db:migrate in either directory I get: rake aborted! No Rakefile found (looking for: rakefile, Rakefile, rakefile.rb, Rakefile.rb) /app/vendor/bundle/ruby/2.2.0/gems/rake-11.2.2/exe/rake:27:in `<top (required)>' (See full trace by running task with --trace) Again, I'm not sure if this has to do with the parent directory having the repo. I understand that there is probably a way for me to point the git repo to the app directory but I'm a little uneasy about messing with files on the remote Github repo. Any other ways to get around this? Thanks! |
Multiple associations to the same model in Rails Posted: 14 Jul 2016 05:45 AM PDT Let's say I have a model Dogs and each dog has exactly 2 Cat "enemies", enemy1 and enemy2 , how do I write the migration file such that I can call dog.enemy1 to retrieve the first enemy and dog.enemy2 to retrieve the second enemy? I tried this: create_table :dog do |t| t.string :name t.timestamps null: false end add_index :dog, :name add_foreign_key :dogs, :cats, column: :enemy1_id add_foreign_key :dogs, :cats, column: :enemy2_id end I also tried it with the t.references method but could not get it to work. Been working on this problem for hours. and it works fine in development but not on Heroku Postgres. The error i get is ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:column "enemy1_id" referenced in foreign key constraint does not exist. Any ideas? |
Rails Mailer does not work when deploying to production Posted: 14 Jul 2016 05:28 AM PDT Following Michael Hartl's tutorial for account activation, when deploying to heroku and creating new user, I get the "We're sorry, but something went wrong." message. The user gets created in the database but the email does not get sent so the account cannot be activated. I don't know why but when getting the "We're sorry..." error, the browser shows me the "....herokuapp.com/users" adress, when the controller says to redirect to root. Hope you can help me, I have been around this for days. Here the users controller: class UsersController < ApplicationController before_action :logged_in_user, only: [:index, :edit, :update, :destroy] before_action :correct_user, only: [:edit, :update] before_action :admin_user, only: :destroy def index @users = User.where(activated: true).paginate(page: params[:page]) end def show @user = User.find(params[:id]) redirect_to root_url and return unless @user.activated? end def new @user = User.new end def create @user = User.new(user_params) if @user.save @user.send_activation_email flash[:info] = "Please check your email to activate your account." redirect_to root_url else render 'new' end end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update_attributes(user_params) flash[:success] = "Profile updated!" redirect_to @user else render 'edit' end end def destroy User.find(params[:id]).destroy flash[:success] = "User deleted!" redirect_to users_url end private def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation) end # Before filters # Confirms a logged-in user. def logged_in_user unless logged_in? store_location flash[:danger] = "Please log in" redirect_to login_url end end # Confirms the correct user. def correct_user @user = User.find(params[:id]) redirect_to(root_url) unless current_user?(@user) end # Confirms an admin user. def admin_user redirect_to(root_url) unless current_user.admin? end end and model: class User < ActiveRecord::Base attr_accessor :remember_token, :activation_token before_save :downcase_email before_create :create_activation_digest # Validates presence and lenght for the user name validates :name, presence: true, length: { maximum: 50 } # Validates presence, length, format and uniqueness for user email VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } # User has a secure password (password_digest), length and presence has_secure_password validates :password, presence: true, length: { minimum: 6 }, allow_nil: true # VALID_PASSWORD_REGEX = "((?=.*\\d)(?=.*[a-z]).{6,20})" # validates :password, format: { with: VALID_PASSWORD_REGEX } # Returns the hash digest of the given string. (only for tests) def User.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end # FOR REMEMBER ME # Returns a random token for safe "remember me". def User.new_token SecureRandom.urlsafe_base64 end # Remembers a user in the database for use in persistent sessions. def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end # Returns true if the given token matches the digest. def authenticated?(attribute, token) digest = send("#{attribute}_digest") return false if digest.nil? BCrypt::Password.new(digest).is_password?(token) end # Forgets a user. def forget update_attribute(:remember_digest, nil) end # Activates an account. def activate update_columns(activated: true, activated_at: Time.zone.now) end # Sends activation email. def send_activation_email UserMailer.account_activation(self).deliver_now end private # Converts email to all lower-case. def downcase_email self.email = email.downcase end # Creates and assigns the activation token and digest. def create_activation_digest self.activation_token = User.new_token self.activation_digest = User.digest(activation_token) end end application and user mailers: class ApplicationMailer < ActionMailer::Base default from: "noreply@example.com" layout 'mailer' end - class UserMailer < ApplicationMailer def account_activation(user) @user = user mail to: @user.email, subject: "Account activation" end end Production.rb Rails.application.configure do config.cache_classes = true config.eager_load = true config.consider_all_requests_local = false config.action_controller.perform_caching = true config.public_file_server.enabled = true config.assets.js_compressor = :uglifier config.assets.compile = false config.assets.digest = true config.force_ssl = true config.log_level = :debug config.action_mailer.raise_delivery_errors = true config.action_mailer.delivery_method = :smtp host = 'whispering-spire-86793.herokuapp.com' config.action_mailer.default_url_options = { host: host } ActionMailer::Base.smtp_settings = { :address => 'smtp.sendgrid.net', :port => '587', :authentication => :plain, :user_name => ENV['SENDGRID_USERNAME'], :password => ENV['SENDGRID_PASSWORD'], :domain => 'heroku.com', :enable_starttls_auto => true } config.i18n.fallbacks = true config.active_support.deprecation = :notify config.log_formatter = ::Logger::Formatter.new config.active_record.dump_schema_after_migration = false end And heroku logs 2016-07-14T12:22:19.113508+00:00 app[web.1]: [3] Puma starting in cluster mode... 2016-07-14T12:22:19.113539+00:00 app[web.1]: [3] * Version 3.4.0 (ruby 2.2.4-p230), codename: Owl Bowl Brawl 2016-07-14T12:22:20.539342+00:00 app[web.1]: [3] * Listening on tcp://0.0.0.0:9375 2016-07-14T12:22:21.039497+00:00 heroku[web.1]: State changed from starting to up 2016-07-14T12:22:22.459846+00:00 heroku[router]: at=info method=POST path="/users" host=whispering-spire-86793.herokuapp.com request_id=7bff9a3c- 3151-48a4-87bc-ba207b1fa10e fwd="88.12.236.151" dyno=web.1 connect=0ms service=390ms status=500 bytes=1714 2016-07-14T12:22:22.684571+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=whispering-spire-86793.herokuapp.com request_id=afd1130c-9864-4650-a5c7-fccd8446039b fwd="88.12.236.151" dyno=web.1 connect=2ms service=2ms status=200 bytes=188 2016-07-14T12:22:23.912741+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=whispering-spire-86793.herokuapp.com request_id=62a47e7f-33c3-42b6-b700-2219cfa8ada1 fwd="88.12.236.151" dyno=web.1 connect=0ms service=3ms status=200 bytes=188 |
action mailer error to deliver email Posted: 14 Jul 2016 05:30 AM PDT I am trying implementing send mail through action mailer in rails related code are.. my mailers/user_mailer.rb class UserMailer < ActionMailer::Base default :from => "debasish@thejaingroup.com" def registration_confirmation(user) mail(:to=>user.email, :subject =>"Registered") end end users.controller is def create @user = User.new(user_params) respond_to do |format| if @user.save UserMailer.registration_confirmation(@user).deliver format.html { redirect_to @user, notice: 'User was successfully created.' } format.json { render :show, status: :created, location: @user } else format.html { render :new } format.json { render json: @user.errors, status: :unprocessable_entity } end end end Here, Your initializer\setup_mail.rb setting will go to the development.rb config.action_mailer.default_url_options = { host: 'localhost', port: 9292 } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { :address =>"smtp.thejaingroup.com", :domain =>"thejaingroup.com", :port => 587, :user_name =>"debasish@thejaingroup.com", :password =>"************" :authentication =>"plain" } and my view is .. user_registration.text.erb ---is Hi sir you successfully Completed signed..........! my have a error msg after running this apps.. SocketError in UsersController#create getaddrinfo: The requested name is valid, but no data of the requested type was found. |
contents disappears when open pdf (created with prawn) in browser Posted: 14 Jul 2016 05:10 AM PDT I have this bounding_box([0, 560], :width => 135, :height => 560) do width, height = 75, 75 soft_mask do # fill_color 0,0,0,0 fill_circle [37, bounds.top - 37], 37 end image @report.account.logo_url, :width => width, :height => height move_down 5 text @report.account.name move_down 3 end when I open pdf file in browser some contents does not shown up but when I comment out soft_mask block and create pdf and try to open in browser every thing works fine what is the reason and how I can fix this. |
Rails remove id=nil from the result Posted: 14 Jul 2016 05:15 AM PDT My Query is - result = Table.select('count(*) as totalCount, sum(price) as totalSum').where('user = ?', id) Returns { "id": null, "totalCount": 3, "totalSum": 300, } But I don't want id. How to remove that id:null |
No comments:
Post a Comment