Rails 5 - How can I make my bootstrap navbar horizontal? Posted: 10 Jan 2017 08:20 AM PST I'm sort of a noob with styling code. And I'd like some help. All the navbars I try to create are vertical in large and small screens. I want an horizontal navbar. I read the bootstrap documentation mentioning @grid-float-breakpoint , but I have no clue how to use it. Here is my application.css.scss: @import "bootstrap"; And my application.html.erb: <!DOCTYPE html> <html> <head> <title>Store</title> <%= csrf_meta_tags %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> </head> <body> <nav class="navbar navbar-light bg-faded"> <a class="navbar-brand" href="#">Navbar</a> <ul class="nav navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> </ul> <form class="form-inline pull-xs-right"> <input class="form-control" type="text" placeholder="Search"> <button class="btn btn-success-outline" type="submit">Seach</button> </form> </nav> <div class="container"> <div class="row"> <div class="col-sm-8"> <%= yield %> </div> <div class="col-sm-4"> <div class="sidebar"> <h3>My sidebar</h3> <p>click</p> <p>click</p> </div> </div> </div> </div> </body> </html> |
Displaying image saved in data type - Rails Posted: 10 Jan 2017 08:19 AM PST I'm trying to display a png image to the screen that is saved in binary in the database. Here is my current attempt and failure messages. Controller: def index @failed_images = FailedImage.order(created_at: :desc).page(params[:page]) end View: <% @failed_images.each do |image| %> <%= image.md5 %> <%= image.data.encode!('UTF-8') %> <% end %> Error: ActionView::Template::Error: "\xEF" from ASCII-8BIT to UTF-8 Basically I just want to display the image on the screen with a size that I can define. I have never done this before so any help would be grand! |
How do I prevent strip from dying when it encounters a non-UTF-8 character without manipulating my string before applying strip? Posted: 10 Jan 2017 08:16 AM PST I'm using Ruby 2.4 with Rails 5. I have the following String 2.4.0 :005 > tr = doc.search("//td").first.text => "\r\n \xA0PLACE \r\n " the String is UTF-8 encoded 2.4.0 :007 > tr = doc.search("//td").first.text.encoding => #<Encoding:UTF-8> but when I apply the "strip" method to it, the call dies 2.4.0 :006 > tr = doc.search("//td").first.text.strip ArgumentError: invalid byte sequence in UTF-8 This is just an example, but how can I override the strip method so it doesn't die when it encounters a character it doesn't like? I don't want to change the string in question. I'm happy to write my own "strip" method, but I want to be able to keep the above exactly as I have it and just not have the error thrown. |
ActionView::Template::Error "Invalid CSS" thrown in feature spec only Posted: 10 Jan 2017 07:46 AM PST The following Sass works perfectly in development: main :not(table) img +box-shadow But when I run my specs, as soon as a JavaScript feature spec is run (which compiles CSS first), it throws the following error: #<ActionView::Template::Error: Invalid CSS after " not(table): img": expected "{", was ";"> I have no idea why this only shows in tests, and not in development. Any ideas? |
Rails sending xml through json post Posted: 10 Jan 2017 07:36 AM PST Trying to send xml text as text in a json post to my rails api. POST request url: localhost:3000/customers/create HEADERS Content-Type: application/json JSON: {"customer": {"name": "bobby", "password": "testingthis", "xml": "<?xml version="1.0" encoding="UTF-8"?> <info> <scope> <vendor id="123456"> <hasp id="880010882479334061"/> </vendor> </scope> </info>"}} Generally, the xml has much more information, but I slimmed it down for this example. I either get a 814: unexpected token or I get a uri too large error. Would you suggest sending it as an xml file rather than text? Any suggestions or help would be gladly accepted. |
Ruby on Rails - where query with Time parse Posted: 10 Jan 2017 07:44 AM PST How can I select all records where the date is past? I have "Date" column with format : '%m/%d/%Y' e.g "01/10/2017". Column type is string, I can't change the type. How should I write query. Something like: Article.where(Time.parse(:date).past?) ? I need solution in pure RoR, without any gem. |
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead Posted: 10 Jan 2017 08:23 AM PST What is happening here? I am trying to add data through ajax call with JSON datatype. But each time I try to add data it shows error as shown in the image. Rails log in terminal I think it always respond to html format but does not respond to json format. def new @batch = Batch.new respond_to do |format| format.json format.html end end def create @batch = Batch.new(batch_param) puts "/n/n/n/n name: #{@batch.name} /n/n/n/n" respond_to do |format| if @batch.save format.json { render json: @batch, status: :created, location: @batch } format.html { redirect_to @batch, notice: "Save process completed!" } else format.html { flash.now[:notice]="Save proccess coudn't be completed!" render :new } format.json { render json: @batch.errors, status: :unprocessable_entity} end end end |
Updating in Rspec isn't working, although the status is 200 Posted: 10 Jan 2017 07:22 AM PST I'm trying to update a User in Rspec: require "rails_helper" RSpec.describe UsersController, type: :controller do describe "PUT #update" do it 'should update a user' do attr1 = { .............. } u1 = User.create!(attr1) put :update, { id: u1.to_param, user: attr1.merge({name: "name2", email: "email2@mail.com"}) }, format: :json u1.reload expect(response.status).to eq(200) expect(u1.name).to eq("name2") The status is 200, but in the body the attributes that are returned aren't updated. |
Rails : get JS variable inside ruby inside inline js Posted: 10 Jan 2017 07:22 AM PST I need to change some div content depending on the link the user clicked. Here is my code :javascript $('.some_clickable_item').on('click', function(e) { clicked_element_id=$(this).data("element_id") $('#my_destination_div').html("#{ render partial: "dashboard/some_partial_name", locals: {item_id: clicked_element_id} }"); }) Obviously, this is not working because clicked_element_id is a js variable, but i need to pass it to my partial. Any simple idea to make it work ? Thanks !! |
Filtered collection select with has many Posted: 10 Jan 2017 07:20 AM PST I'm with some trouble to build a form with a filtered collection select for a Model that has a "has many" association. Basically an "Anuncio" (listing) can have multiple "Atributos" (attributes) and can also belongs to many of those "Atributos". An "Atributo" belongs to a "Categoria Marketplace" (marketplace category) and also has and belongs to many "Anuncios". These "Atributos" are registered by an Admin (this part is already done) and they have a type and value (besides the marketplace category). The problem is the form for someone creating/editing an "Anuncio" and making the Associations. The "Anuncio" has a specific set of "Atributos" that they can have, driven by the marketplace category that the "Anuncio" and the "Atributo" share. The important parts (models in the end, they seems ok for me but just for the record): Editing the "Atributos" of an "Anuncio": def anuncio_edit @anuncio = Marketplace::Anuncio.find(params[:id]) @atributos= @anuncio.categoria_marketplace.atributos.select("DISTINCT TIPO") if @anuncio.atributos.empty? @anuncio.atributos.build end end The form (tentative): <%= form_for @anuncio, :url => edit_anuncio_atributo_path, :html => { :multipart => true } do |f| %> <div class="panel panel-default top15"> <div class="panel-heading" style="background-color: #c8d3d5"> <h3 class="panel-title" style="font-size: 18px;">Editando atributos: <%=@anuncio.titulo%> (ID: <%=@anuncio.id%>) de <%=@anuncio.musico.name%></h3> </div> <div class="panel-body"> <%@atributos.each do |atributo|%> <div class="col-md-12"> <div class="col-md-4 form-group"> <%=atributo.tipo%> <%= f.fields_for :atributos do |att|%> <%= att.collection_select(:id, Marketplace::Atributo.where(:tipo => atributo.tipo), :id, :valor,{:include_blank => true}, {class: "form-control"})%> <%end%> </div> </div> <%end%> <div class="col-md-12"> <div class="col-md-4 col-md-offset-4"> <%= f.submit "Atualizar Atributos", data: { disable_with: "Validando..." }, class: "btn btn-block btn-mj"%> </div> </div> </div> </div> <%end%> And the output: I'm trying to simply show a list of the Attributes that can be display for that "Anuncio" in a collection select already filtered by it's type. anuncio.rb ... has_many :anuncio_atributos, :dependent => :destroy has_many :atributos, -> { uniq }, :through => :anuncio_atributos ... atributos.rb has_many :anuncio_atributos, :dependent => :destroy has_many :anuncios, -> { uniq }, :through => :anuncio_atributos belongs_to :categoria_marketplace anuncio_atributo.rb belongs_to :atributo belongs_to :anuncio end |
Rails 4, Capistrano 3 and Dotenv - How to deploy using server-side .env file Posted: 10 Jan 2017 07:38 AM PST I have a Rails 4 app with Dotenv gem to read variables from the file .env . There are some variables I've set in order to have a mysql user other than "root" for my rails app, for example: MYSQL_ROOT_USER='rootuser' MYSQL_ROOT_PASSWORD='rootpassword' APP_DATABASE_USER='mydbuser' APP_DATABASE_PASSWORD='userpassword' I've also created a bash script to create the mysql user under scripts/database_setup.bash #!/bin/bash source ../.env # creates the user mysql -u${MYSQL_ROOT_USER} --password="${MYSQL_ROOT_PASSWORD}" -e "CREATE USER '${APP_DATABASE_USER}'@'localhost' IDENTIFIED BY '${APP_DATABASE_PASSWORD}';" # grants permission mysql -u${MYSQL_ROOT_USER} --password="${MYSQL_ROOT_PASSWORD}" -e "GRANT ALL PRIVILEGES ON \`myapp\_%\`.* TO '${APP_DATABASE_USER}'@'localhost';" On the server side, Capistrano deploys to `/home/myuser/apps/myapp/ I have three questions: - Where is the best place to put my server-side
.env file? Right now I'm putting it in /home/myuser/apps/myapp/ directory. - How can I tell Capistrano to copy it to Rails root directory?
- How can I tell Capistrano to execute my bash script before running migrations?
|
Rails 5 instance level helpers method in controller not recognizing helpers. method Posted: 10 Jan 2017 07:53 AM PST I'm trying to follow the "New way to call helper methods in Rails 5" mentioned here, originally PR here. I can get the "old approach" to work with the following: # app/models/order.rb class Customer < ActiveRecord::Base include CustomersHelper # some code... def name_make_uppercase self.first_name = uppercase(first_name) self.last_name = uppercase(last_name) end end # app/helperss/customers_helper.rb module CustomersHelper def uppercase(input) return unless input input[0] = input[0].to_s.capitalize input end end However, with the new approach I believe I should be able to remove the "include CustomersHelper" and add "helpers." to my uppercase functions in the controller e.g. # app/models/order.rb class Customer < ActiveRecord::Base # include CustomersHelper # some code... def name_make_uppercase self.first_name = helpers.uppercase(first_name) self.last_name = helpers.uppercase(last_name) end end However, now my spec's are getting the following error: NameError: undefined local variable or method `helpers' for #Customer:0x00000004d50be8> I'm curious what I might be doing wrong. |
collection_select concat firstname and lastname with same id Posted: 10 Jan 2017 07:32 AM PST I'm trying to get the firstname(s) and lastname(s) which have the same id. My Table Schema looks like this: | id | nameable_id | nameable_type | value | type | | 1 | 2 | Person | John | Firstname | | 2 | 2 | Person | Doe | Lastname | I want to use a collection_select with an expected output: <select name="source[person_id]" id="source_person_id"> <option value="2">John Doe</option></select>` How can I concatenate these values with the same nameable_id and order the firstname(s) then the lastname(s)? |
Ransack query on multiple fields with curl Posted: 10 Jan 2017 06:48 AM PST Using the Ransack Rubygem, I am trying to make a query against two conditions using a curl. This for searching ability being added to an API. Query on a single field curl -X GET -G 'http://localhost:3000/api/v2/products' -d 'q[barcode_eq]=7610200237576' This works Processing by Api::V2::ProductsController#index as */* Parameters: {"q"=>{"barcode_eq"=>"761063205021"}} Product Load (0.4ms) SELECT "products".* FROM "products" WHERE "products"."barcode" = '761063205021' LIMIT 50 OFFSET 0 Query on two fields curl -X GET -G 'http://localhost:3000/api/v2/products' -d 'q[barcode_eq]=7610200237576' -d 'q[barcode_eq]=7616800205113' Ignores the first query Started GET "/api/v2/products?q[barcode_eq]=7610200237576&q[barcode_eq]=7616800205113" for ::1 at 2017-01-10 15:34:28 +0100 Processing by Api::V2::ProductsController#index as */* Parameters: {"q"=>{"barcode_eq"=>"7616800205113"}} Product Load (0.6ms) SELECT "products".* FROM "products" WHERE "products"."barcode" = '7616800205113' LIMIT 50 OFFSET 0 What is the correct sentence to search (and / or) against multiple fields using curl or via ajax. |
Ruby on Rails - Transform base64 into image file without saving to use in multipart API call Posted: 10 Jan 2017 06:32 AM PST I'm using RoR and I have a base 64 encoded image image_base64 = "data:image/jpeg;base64,/9j/4AAQSkZ..." . An API asks me to upload it as JPG file in a multipart/form-data parameter - e.g curl -X POST -F "images_file=@my_image.jpg" I know how to turn the base 64 image into a file that would be saved somewhere (like in this other SO question), but I don't really want to be saving and deleting files, just create one on the fly. How can I do that? |
How to decrease varchar of MySQL column which exists value with Rails migration? Posted: 10 Jan 2017 06:23 AM PST I want to migrate table column length 255 to 191 to change characterset from utf8 to utf8mb4. Rails migration is below. def self.up change_column :friend_user_lists, :comment, :string, :limit => 191 end I already changed database, table and column charset to utf8mb4, and got an error below. Mysql::Error: Data truncated for column 'comment' at row 118: ALTER TABLE `friend_user_lists` CHANGE `comment` `comment` varchar(191) DEFAULT NULL I guess that the error shows that too much long values exist. Then how to migrate? |
Can I get a ActiveRecord::Connection instance from a ActiveRecord::StatementInvalid exception? Posted: 10 Jan 2017 06:01 AM PST I'm performing a complex data import task, using multiple PostgreSQL database connections. Under certain conditions I need to perform a rollback on a specific database connection if I encounter a ActiveRecord::StatementInvalid exception. I cannot seem to get the ActiveRecord::Connection instance from that exception. What I can get is a PG::Connection instance from exception.original_exception.connection . Unfortunately I need the ActiveRecord instance to properly perform the rollback and keep the internal AR data structures in sync with the database. At the very least I need the name of the last savepoint, if any, to perform a manual rollback. How can I get a ActiveRecord::Connection instance from a ActiveRecord::StatementInvalid exception? |
Ruby on Rails - Changing nested keys name Posted: 10 Jan 2017 06:09 AM PST I'm a newbie on Rails and I'm trying to avoid conflicts with Rails reserved names in a Controller that's receiving JSON The code: class TransactionsController < ApplicationController #before_action :set_origin_transaction, only: [:show, :edit, :update, :destroy] skip_before_action :verify_authenticity_token, :only => [:create] def create total = origin_transaction_params[:total] outputs_value = origin_transaction_params[:origin_inputs_attributes][:output_value] binding.pry origin_inputs_addresses = origin_transaction_params[:origin_inputs_attributes][:addresses] origin_outputs_value = origin_transaction_params[:origin_outputs_attributes][:output_value] origin_outputs_addresses = origin_transaction_params[:origin_outputs_attributes][:addresses] puts "total: " + total + "outputs_value: " + origin_outputs_value + "inputs_addresses: " + origin_inputs_addresses puts "outputs_value: " + origin_outputs_value + "outputs_addresses: " + origin_outputs_addresses end # This is made to avoid using reserved names of ruby (transaction, inputs, outputs, etc), we change the keys private def origin_transaction_params params.deep_transform_keys! { |key| key == "hash" ? "origin_hash" : ( key == "inputs" ? "origin_inputs_attributes" : ( key == "outputs" ? "origin_outputs_attributes" : ( key == "addresses" ? "btcaddresses" : key))) } params.permit( :block_height, :block_index, :origin_hash, :total, :fees, :size, :preference, :relayed_by, :received, :ver, :lock_time, :double_spend, :vin_sz, :vout_sz, :confirmations, :origin_inputs_attributes => [ :prev_hash, :output_index, :script, :output_value, :sequence, :btcaddresses, :script_type ], :origin_outputs_attributes => [ :value, :script, :btcaddresses, :script_type ]) end end The error: Processing by TransactionsController#create as */* Parameters: {"block_height"=>-1, "block_index"=>-1, "hash"=>"4f14eb3517c92221892d7b86b4e691de404dddecbcc5d6d03148de8b1a6aceb8", "addresses"=>["12onkFjRFBdmgAMW5fapaGfo8E2PWxNRbb", "191JF8jDaCCADJsjrx171fd6PE6D9YtGoi", "1MGHXDQAA4mfBSLK4Dt3QDrAXNcXaaW7JY", "1PZCBuJC53HwjVhXb5B1rA4uFhrHrqrUUC"], "total"=>183092, "fees"=>33660, "size"=>372, "preference"=>"high", "relayed_by"=>"67.205.175.175:8333", "received"=>"2017-01-02T00:59:06.751Z", "ver"=>1, "lock_time"=>0, "double_spend"=>false, "vin_sz"=>2, "vout_sz"=>2, "confirmations"=>0, "inputs"=>[{"prev_hash"=>"dcb03a8c3dc38e28376b5b97479b06c383813c3fc5bcc66fb59c4967b85436c3", "output_index"=>1, "script"=>"47304402205c1cdd0cf3f789375a6dfc0c76eba142724edda2473b235547b7275f7dd0f1c4022046ec4f0be0726d848f6ccd1467b04023897e4575988115c0ac8dbaf569fe03da012102a6237f2117e38d566581452171cff013cfee6f69d5af84fab2214350882a81d9", "output_value"=>108376, "sequence"=>4294967295, "addresses"=>["12onkFjRFBdmgAMW5fapaGfo8E2PWxNRbb"], "script_type"=>"pay-to-pubkey-hash"}, {"prev_hash"=>"9609e8f8a18a11ce54f2b726df5cee24e4589a03feef9b121be5a2eb4ce27ce0", "output_index"=>1, "script"=>"47304402207a29300f3570b5d635b344e3fdc38b3906cb7712870a4a775b4a10cb000b0b6202207ffbd30d0ad0cafb1e93253b17ab302583816c8e17d9d15114c544a6614c9e3201210314fd8f972f8d3e840dfeee629dc5bdcb81c272334c6b23ff34ccd5cbc761fadd", "output_value"=>108376, "sequence"=>4294967295, "addresses"=>["1PZCBuJC53HwjVhXb5B1rA4uFhrHrqrUUC"], "script_type"=>"pay-to-pubkey-hash"}], "outputs"=>[{"value"=>82592, "script"=>"76a91457cf668b86c09b50e1fe89fac148ba321380d54588ac", "addresses"=>["191JF8jDaCCADJsjrx171fd6PE6D9YtGoi"], "script_type"=>"pay-to-pubkey-hash"}, {"value"=>100500, "script"=>"76a914de468bcbc3c1bf0e25dd9b626c60eac3a8d8d91488ac", "addresses"=>["1MGHXDQAA4mfBSLK4Dt3QDrAXNcXaaW7JY"], "script_type"=>"pay-to-pubkey-hash"}], "transaction"=>{"block_height"=>-1, "block_index"=>-1, "hash"=>"4f14eb3517c92221892d7b86b4e691de404dddecbcc5d6d03148de8b1a6aceb8", "addresses"=>["12onkFjRFBdmgAMW5fapaGfo8E2PWxNRbb", "191JF8jDaCCADJsjrx171fd6PE6D9YtGoi", "1MGHXDQAA4mfBSLK4Dt3QDrAXNcXaaW7JY", "1PZCBuJC53HwjVhXb5B1rA4uFhrHrqrUUC"], "total"=>183092, "fees"=>33660, "size"=>372, "preference"=>"high", "relayed_by"=>"67.205.175.175:8333", "received"=>"2017-01-02T00:59:06.751Z", "ver"=>1, "lock_time"=>0, "double_spend"=>false, "vin_sz"=>2, "vout_sz"=>2, "confirmations"=>0, "inputs"=>[{"prev_hash"=>"dcb03a8c3dc38e28376b5b97479b06c383813c3fc5bcc66fb59c4967b85436c3", "output_index"=>1, "script"=>"47304402205c1cdd0cf3f789375a6dfc0c76eba142724edda2473b235547b7275f7dd0f1c4022046ec4f0be0726d848f6ccd1467b04023897e4575988115c0ac8dbaf569fe03da012102a6237f2117e38d566581452171cff013cfee6f69d5af84fab2214350882a81d9", "output_value"=>108376, "sequence"=>4294967295, "addresses"=>["12onkFjRFBdmgAMW5fapaGfo8E2PWxNRbb"], "script_type"=>"pay-to-pubkey-hash"}, {"prev_hash"=>"9609e8f8a18a11ce54f2b726df5cee24e4589a03feef9b121be5a2eb4ce27ce0", "output_index"=>1, "script"=>"47304402207a29300f3570b5d635b344e3fdc38b3906cb7712870a4a775b4a10cb000b0b6202207ffbd30d0ad0cafb1e93253b17ab302583816c8e17d9d15114c544a6614c9e3201210314fd8f972f8d3e840dfeee629dc5bdcb81c272334c6b23ff34ccd5cbc761fadd", "output_value"=>108376, "sequence"=>4294967295, "addresses"=>["1PZCBuJC53HwjVhXb5B1rA4uFhrHrqrUUC"], "script_type"=>"pay-to-pubkey-hash"}], "outputs"=>[{"value"=>82592, "script"=>"76a91457cf668b86c09b50e1fe89fac148ba321380d54588ac", "addresses"=>["191JF8jDaCCADJsjrx171fd6PE6D9YtGoi"], "script_type"=>"pay-to-pubkey-hash"}, {"value"=>100500, "script"=>"76a914de468bcbc3c1bf0e25dd9b626c60eac3a8d8d91488ac", "addresses"=>["1MGHXDQAA4mfBSLK4Dt3QDrAXNcXaaW7JY"], "script_type"=>"pay-to-pubkey-hash"}]}} DEPRECATION WARNING: Method deep_transform_keys! is deprecated and will be removed in Rails 5.1, as `ActionController::Parameters` no longer inherits from hash. Using this deprecated behavior exposes potential security problems. If you continue to use this method you may be creating a security vulnerability in your app that can be exploited. Instead, consider using one of these documented methods which are not deprecated: http://api.rubyonrails.org/v5.0.1/classes/ActionController/Parameters.html (called from origin_transaction_params at /var/www/html/hubble/app/controllers/transactions_controller.rb:23) Unpermitted parameter: btcaddresses Unpermitted parameter: btcaddresses Unpermitted parameter: btcaddresses Unpermitted parameter: btcaddresses Unpermitted parameters: btcaddresses, transaction DEPRECATION WARNING: Method deep_transform_keys! is deprecated and will be removed in Rails 5.1, as `ActionController::Parameters` no longer inherits from hash. Using this deprecated behavior exposes potential security problems. If you continue to use this method you may be creating a security vulnerability in your app that can be exploited. Instead, consider using one of these documented methods which are not deprecated: http://api.rubyonrails.org/v5.0.1/classes/ActionController/Parameters.html (called from origin_transaction_params at /var/www/html/hubble/app/controllers/transactions_controller.rb:23) Unpermitted parameter: btcaddresses Unpermitted parameter: btcaddresses Unpermitted parameter: btcaddresses Unpermitted parameter: btcaddresses Unpermitted parameters: btcaddresses, transaction Completed 500 Internal Server Error in 13ms (ActiveRecord: 0.0ms) TypeError (no implicit conversion of Symbol into Integer): app/controllers/transactions_controller.rb:9:in `[]' Thanks a lot BTW, I would also like to stop using the deprecated method, but I'm not so sure about what I should use |
Rails 5 access profile data anywhere in session without querying database each time Posted: 10 Jan 2017 06:10 AM PST I've a user profile (with name, logo, about_me) which is created after user creation(using Devise). Profile table uses user_id as Primary key. Now I want that whenever the user creates/updates a post, while filling in form some details are taken from profile, so profile data or @profile be available in post form as I cannot expose my model in form. To set post.myname attribute in create and #update I'm doing this: @myprofile = Profile.find_by_user_id(current_user) write_attribute(:myname, @myprofile.name) I read from various sources but what's the best solution of the 4 given and if anyone can back with easy code as I do not want to do something extensive? Thanks in advance. 1)Form Hidden fields - Like get the profile data as above in hash in #edit and then pass through form and access fields in #update but that way we will pass each field separately. Can one @myprofile be passed? 2)Session - I feel if profile data is stored in a session and someone updates profile then updated data won't be available in that session.So not sure if it is plausible. 3)Caching - easy way to do that? 4)polymorphic profile---tried it but I didnot get relevant example. I was stuck with what to put as profileable id and type and how to use them in the code. |
Can't create model on ruby on rails Posted: 10 Jan 2017 06:36 AM PST I'm starting to learn ruby on rails. the problem that i have is that i don't know why i get there while i want to create model this is the command that i tried rails generate model Book and get this error in my ubuntu 16 terminal /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.0.1/lib/rails/app_loader.rb:40: warning: Insecure world writable dir /opt in PATH, mode 040777 /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.0.1/lib/rails/application/configuration.rb:148:in `rescue in database_configuration': YAML syntax error occurred while parsing /home/android/ruby Tutorial/library/config/database.yml. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Error: (<unknown>): found a tab character that violate intendation while scanning a plain scalar at line 17 column 10 (RuntimeError) from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.0.1/lib/rails/application/configuration.rb:131:in `database_configuration' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activerecord-5.0.1/lib/active_record/railtie.rb:122:in `block (2 levels) in <class:Railtie>' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.0.1/lib/active_support/lazy_load_hooks.rb:43:in `instance_eval' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.0.1/lib/active_support/lazy_load_hooks.rb:43:in `execute_hook' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.0.1/lib/active_support/lazy_load_hooks.rb:50:in `block in run_load_hooks' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.0.1/lib/active_support/lazy_load_hooks.rb:49:in `each' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.0.1/lib/active_support/lazy_load_hooks.rb:49:in `run_load_hooks' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activerecord-5.0.1/lib/active_record/base.rb:324:in `<module:ActiveRecord>' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activerecord-5.0.1/lib/active_record/base.rb:24:in `<top (required)>' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:293:in `require' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:293:in `block in require' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:259:in `load_dependency' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:293:in `require' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/application.rb:345:in `active_record_configured?' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/application.rb:263:in `disconnect_database' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/application.rb:97:in `preload' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/application.rb:143:in `serve' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/application.rb:131:in `block in run' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/application.rb:125:in `loop' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/application.rb:125:in `run' from /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/application/boot.rb:19:in `<top (required)>' from /home/android/.rbenv/versions/2.3.3/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from /home/android/.rbenv/versions/2.3.3/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from -e:1:in `<main>' i also tried this rails script/generate model Book and i get this error: /home/android/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.0.1/lib/rails/app_loader.rb:40: warning: Insecure world writable dir /opt in PATH, mode 040777 rails aborted! Don't know how to build task 'script/generate' (see --tasks) /home/android/ruby Tutorial/library/bin/rails:9:in `require' /home/android/ruby Tutorial/library/bin/rails:9:in `<top (required)>' /home/android/ruby Tutorial/library/bin/spring:14:in `<top (required)>' bin/rails:3:in `load' bin/rails:3:in `<main>' (See full trace by running task with --trace) //Edit I check my database but and also check yamlint website also has error on line 17 but there is no error # SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' # default: &default adapter: mysql pool: 5 timeout: 5000 development: adapter: mysql database: library_development username: root password: root1234 host: localhost test: adapter: mysql database: library_test username: root password: root1234 host: localhost production: adapter: mysql database: library_production username: root password: root1234 host: localhost |
wicked_pdf shows unknown character on unicode pdf conversion (ruby) Posted: 10 Jan 2017 05:47 AM PST I'm trying to create a pdf from a html page using wicked_pdf (version 1.1) and wkhtmltopdf-binary gems. My html page contains a calendar emoji that displays well in the browser whatever font I use <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv='content-type' content='text/html; charset=utf-8' /> <style> unicode { font-family: 'OpenSansEmoji', sans-serif; } @font-face { font-family: 'OpenSansEmoji'; src: url(data:font/truetype;charset=utf-8;base64,<-- encoded_font_base64_string-->) format('truetype'); } </style> </head> <body> <div><unicode>📅</unicode></div> </body> </html> However, when I try to generate the PDF using the WickedPdf.new.pdf_from_html_file method of the gem in the rails console, File.open(File.expand_path('~/<--pdf_filename-->.pdf'), 'wb+') {|f| f.write WickedPdf.new.pdf_from_html_file('<--absolute_path_of_html_file-->')} I get the following result: PDF result result with unknown character I have investigated through encoding in UTF-8 and UTF-16 and surrogate pair as suggested by this related post stackoverflow_emoji_wkhtmltopdf and looked at this issue wkhtmltopdf_git_issue but still can't make this character disappear! If you have any clue, it's more than welcome. Thanks in advance for your help! |
JSON query combined with other data types Posted: 10 Jan 2017 07:20 AM PST I have a Contact model with a string and json attribute the string attribute stores the phone_number and the json attribute stores some other data. I want to run a query like this Contact.exists?(phone_number: '+255788778899', data: {name: 'Gamma', region: 'The Great one'}) I have searched all over google and SO, but most of the articles simple give a way of find the record with a json string only and which has only one key e.g Contact.exists?("data ->> 'name' = 'Gamma'") However my intention is to find if a contact exists with the phone number and the full json attribute specified in the same query How can I do this? |
Get meta tags from external URL using Ruby on Rails and Ajax Posted: 10 Jan 2017 05:38 AM PST I'm creating a form which contains the fields "URL", "Title" and "Image". I'd like to update the value of title and image textboxes when user paste a URL in the first field(onkeyup). These values could come from meta tags. How can I do it? Thanks. |
Is there any way i can execute selenium script using ruby code and get response? Posted: 10 Jan 2017 05:30 AM PST If any website/opensource tool developed using rails which allow to upload selenium script and execute it. |
Issues with a tag system's creation Posted: 10 Jan 2017 05:48 AM PST I am following this tutorial to create some custom tags. I the instructions excepted for the AJAX and Foundation part since I haven't built my website this way. I'm experiencing an issue with the "tag research" part when you only need to click on a tag to see all posts about the tag, Rails tells me the following: undefined method `articles' for #<Tag:0x007f0a690eeb40> Here are my files adapted from the tutorial: article.rb class Article < ApplicationRecord mount_uploader :image, ArticleUploader extend FriendlyId friendly_id :titre, use: :slugged has_many :taggings has_many :tags, through: :taggings def all_tags=(names) self.tags = names.split(',').map do |name| Tag.where(name: name.strip).first_or_create! end end def all_tags self.tags.map(&:name).join(", ") end def self.tagged_with(name) Tag.find_by_name!(name).articles # Issue comes from here end end tag.rb class Tag < ApplicationRecord has_many :taggings has_many :tags, through: :taggings end tagging.rb class Tagging < ApplicationRecord belongs_to :article belongs_to :tag end config/routes.rb get 'tags/:tag', to: 'articles#index', as: "tag" resources :articles Please ask if you need to see something else As you can see, i simply used my 'Article' model that already existed when starting the tutorial, so I used 'articles' instead of 'posts' as the author asked. I can't find anything related on Google and i'm not working with any IDE right now so I have no clue about what to do.. Any help is welcomed! |
Shopify : User maintain product at cart page Posted: 10 Jan 2017 05:52 AM PST I have an doubt and explain with example. User A, logged into the site and added the 3 ( Ball, bat and pen) products in Cart page and then logged out form the site. Few days later, the Same User A, logged into the site using other devices or browser( Not same browser). On that case we need to display the same 3 ( Ball, bat and pen) products in Cart page. How to implement this process to out site. please give the solution for this scenario. Thanks, Karthik |
Custom navigation links in rails admin Posted: 10 Jan 2017 05:11 AM PST In my project I'm using rails_admin gem to get admin panel functionality. I have on issue with this gem. How can I add custom links to navigation header? By default there are two links: Home and Dashboard . |
Convert any xpath to css selector in Ruby Posted: 10 Jan 2017 05:09 AM PST I have a Rails application where the user (trained to do so) introduces an xpath for a specific element on an html page. The users are not trained in CSS selectors so I prefer not to re-train them. I then need to export the xpath to a css selector so it can be used to attach actions on the element on the client side in a browser-run JS script. Is there a gem that can do this? I can see Nokogiri has an xpath_for method that can convert CSS to Xpath but not the reverse. As an alternative, I can convert the xpath to css at runtime with JS using this NPM library (I need to port it to browser-compatible JS first) - but I prefer to convert the xpath server-side. |
Elasticsearch-rails results not as expected Posted: 10 Jan 2017 05:04 AM PST I am using elasticsearch-rails and elasticsearch-model gem for searching words in my rails app. Here is my model where I want to search to take place require 'elasticsearch/model' class Article < ActiveRecord::Base include Elasticsearch::Model include Elasticsearch::Model::Callbacks settings index: { number_of_shards: 1 } do mappings dynamic: 'false' do indexes :title, analyzer: 'english', index_options: 'offsets' indexes :text, analyzer: 'english' end end def self.search(query) __elasticsearch__.search( { query: { multi_match: { query: query, fields: ['title^10', 'text'] } }, highlight: { pre_tags: ['<em>'], post_tags: ['</em>'], fields: { title: {}, text: {} } } } ) end end # Delete the previous articles index in Elasticsearch Article.__elasticsearch__.client.indices.delete index: Article.index_name rescue nil # Create the new index with the new mapping Article.__elasticsearch__.client.indices.create \ index: Article.index_name, body: { settings: Article.settings.to_hash, mappings: Article.mappings.to_hash } # Index all article records from the DB to Elasticsearch Article.import #Article.import force: true My questions are how do I do search Composite matching? Example: If my database contain names -sachin shah -sachin mehta -rohan patil -kumar sachin If I search sachin keyword, I want all record which contains sachin. |
Define assets precompile for every controller in Rails 5 Posted: 10 Jan 2017 04:57 AM PST I am familiar with Rails already but I downloaded a Rails demo App to see some best practices. My question is about the asset pipeline which is still confusing to me. In my other Rails app I have one JS and one CSS file for every controller and I can write whatever I want in there and it works. In my demo app I find those two lines: <!-- =============== VIEW VENDOR STYLES ===============--> <%= stylesheet_link_tag params[:controller] %> <!-- =============== VIEW VENDOR SCRIPTS ===============--> <%= javascript_include_tag params[:controller] %> When I start my App I get an error and to solve this I have to add these two lines Rails.application.config.assets.precompile += %w( xxx.css ) Rails.application.config.assets.precompile += %w( xxx.js ) for every controller to my initializers/assets.rb file. Is somehow annoying. What is this all about? |
No comments:
Post a Comment