Monday, July 11, 2016

Rails 'select' form for Delete method of RESTful resource | Fixed issues

Rails 'select' form for Delete method of RESTful resource | Fixed issues


Rails 'select' form for Delete method of RESTful resource

Posted: 11 Jul 2016 08:40 AM PDT

This seems like it should be a simple thing, but I haven't been able to hunt down an illustrative example. Apologies if this question is redundant.

So I have a rails app, and I'm trying to work with a RESTful resource. This is what the route looks like:

config/routes.rb

resources :articles, only: [:index, :create, :destroy]  

I want a simple form to delete these in case extras are added or whatever. So here are the form and controller I have so far:

app/views/articles/_delete.html.haml

%h1 Delete Article  - all_articles = Article.all.sort.reverse.map { |a| [a.name, a.id] }  = form_for @article, method: :delete do |f|    .form-group      = f.select :id, options_for_select(all_articles), class: 'form-control'    = f.submit 'Delete', class: 'btn btn-danger'  

When I submit this, I get 'No route matches [DELETE] "/articles"'. This is because the route for deletion is articles/:id :

DELETE    /articles/:id(.:format)    articles#destroy  

So my goal is to get the submit button to grab the id, and send off to /articles/:id with the Delete method. If it helps, I'm on Rails 4.1.

I think the real pain point for me here though is not fully understanding how the form helper points to an action or passes data around. If anyone can elucidate I'd be appreciative.

I see that I can define a url on the form_for method, like so:

= form_for @article, method: :delete, url: articles_path do |f|  

But how can I get the id from the form into that url?

First capistrano deploy does't make any effect

Posted: 11 Jul 2016 08:28 AM PDT

how is it going? I have a Rails 4 app and I'm trying to deploy it with capistrano 3 on my server.

I already installed with bundle install and cap install, generating the files. I already added my info com deploy.rb file and when I run the command for the first deploy, it doesn't print the log on my console and do any effect.

usuario$ cap production deploy  usuario$  

I ran this command with the --trace to see more details:

usuario$ cap production deploy --trace  ** Invoke production (first_time)  ** Execute production  ** Invoke load:defaults (first_time)  ** Execute load:defaults  ** Invoke rvm:hook (first_time)  ** Invoke passenger:rvm:hook (first_time)  ** Invoke passenger:test_which_passenger (first_time)  ** Execute passenger:test_which_passenger  ** Execute passenger:rvm:hook  ** Execute rvm:hook  ** Invoke rvm:check (first_time)  ** Execute rvm:check  ** Invoke bundler:map_bins (first_time)  ** Invoke passenger:bundler:hook (first_time)  ** Execute passenger:bundler:hook  ** Execute bundler:map_bins  ** Invoke deploy:set_rails_env (first_time)  ** Execute deploy:set_rails_env  ** Invoke deploy:set_linked_dirs (first_time)  ** Execute deploy:set_linked_dirs  ** Invoke deploy:set_rails_env   ** Invoke deploy (first_time)  ** Execute deploy  ** Invoke deploy:starting (first_time)  ** Execute deploy:starting  ** Invoke deploy:check (first_time)  ** Execute deploy:check  ** Invoke git:check (first_time)  ** Invoke git:wrapper (first_time)  ** Execute git:wrapper  ** Execute git:check  ** Invoke deploy:check:directories (first_time)  ** Execute deploy:check:directories  ** Invoke deploy:check:linked_dirs (first_time)  ** Execute deploy:check:linked_dirs  ** Invoke deploy:check:make_linked_dirs (first_time)  ** Execute deploy:check:make_linked_dirs  ** Invoke deploy:check:linked_files (first_time)  ** Execute deploy:check:linked_files  ** Invoke deploy:set_previous_revision (first_time)  ** Execute deploy:set_previous_revision  ** Invoke deploy:started (first_time)  ** Execute deploy:started  ** Invoke deploy:updating (first_time)  ** Invoke deploy:new_release_path (first_time)  ** Execute deploy:new_release_path  ** Execute deploy:updating  ** Invoke git:create_release (first_time)  ** Invoke git:update (first_time)  ** Invoke git:clone (first_time)  ** Invoke git:wrapper   ** Execute git:clone  ** Execute git:update  ** Execute git:create_release  ** Invoke deploy:set_current_revision (first_time)  ** Execute deploy:set_current_revision  ** Invoke git:set_current_revision (first_time)  ** Execute git:set_current_revision  ** Invoke deploy:symlink:shared (first_time)  ** Execute deploy:symlink:shared  ** Invoke deploy:symlink:linked_files (first_time)  ** Execute deploy:symlink:linked_files  ** Invoke deploy:symlink:linked_dirs (first_time)  ** Execute deploy:symlink:linked_dirs  ** Invoke deploy:updated (first_time)  ** Invoke bundler:install (first_time)  ** Execute bundler:install  ** Execute deploy:updated  ** Invoke deploy:compile_assets (first_time)  ** Invoke deploy:set_rails_env   ** Execute deploy:compile_assets  ** Invoke deploy:assets:precompile (first_time)  ** Execute deploy:assets:precompile  ** Invoke deploy:assets:backup_manifest (first_time)  ** Execute deploy:assets:backup_manifest  ** Invoke deploy:cleanup_assets (first_time)  ** Invoke deploy:set_rails_env   ** Execute deploy:cleanup_assets  ** Invoke deploy:normalize_assets (first_time)  ** Invoke deploy:set_rails_env   ** Execute deploy:normalize_assets  ** Invoke deploy:migrate (first_time)  ** Invoke deploy:set_rails_env   ** Execute deploy:migrate  ** Invoke deploy:publishing (first_time)  ** Execute deploy:publishing  ** Invoke deploy:symlink:release (first_time)  ** Execute deploy:symlink:release  ** Invoke deploy:restart (first_time)  ** Execute deploy:restart  ** Invoke passenger:restart (first_time)  ** Execute passenger:restart  ** Invoke deploy:published (first_time)  ** Execute deploy:published  ** Invoke deploy:finishing (first_time)  ** Execute deploy:finishing  ** Invoke deploy:cleanup (first_time)  ** Execute deploy:cleanup  ** Invoke deploy:finished (first_time)  ** Execute deploy:finished  ** Invoke deploy:log_revision (first_time)  ** Execute deploy:log_revision  usuario$   

...and anything was created on the server (current and release folder).

Any ideas what I'm doing wrong? I appreciate any clue.

EDIT

That is my deploy.rb

# config valid only for current version of Capistrano  lock '3.5.0'    set :application, 'my_app_name'  set :repo_url, 'my_user@my_server_ip:/my_path_to/app_repo.git'    set :deploy_to, "/var/www/my_app_name"  set :default_stage, "production"  set :linked_files, fetch(:linked_files, []).push('config/database.yml')  set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system', 'public/uploads')    set :keep_releases, 3  set :default_env, { rvm_bin_path: '~/.rvm/bin' }  

Creating two-self joins that share the same parent id

Posted: 11 Jul 2016 07:32 AM PDT

I've setup two self-joins for my Album model. The first is for album singles. The second is for editions that an album may have (Deluxe Edition, Japanese Edition, etc). Both singles and editions share the exact attributes/associations (name, release date, tracks) which is why I chose to use self-joins vs. creating separate models.

For these two self-joins I've created one foreign key, parent_album, since a single and/or edition essentially derives from that one album. I was wondering if it were possible to have self-joins share the same foreign key, parent_album_id or do I need to create one for each? Currently if I were to assign a single/edition to an album they would fall in to either collection.

class Album < ApplicationRecord    has_many :singles, class_name: "Album", foreign_key: "parent_album_id"    belongs_to :parent_album, class_name: "Album", optional: true      has_many :editions, class_name: "Album", foreign_key: "parent_album_id"    belongs_to :parent_album, class_name: "Album", optional: true  end  

extconf failed, exit code 1 error when installing [Ruby on Rails] 5 on OS X Yosemite 10.10.5

Posted: 11 Jul 2016 08:30 AM PDT

I'm trying to install Ruby on Rails v5 on OS X Yosemite 10.10.5, following the instructions on the rails site:

http://railsapps.github.io/installrubyonrails-mac.html

When I run this:

sudo gem install rails --version 5.0.0 --no-ri --no-rdoc  

I get the error ERROR: Failed to build gem native extension. Here are parts of the output on my command line that might be useful:

current directory: /Users/me/.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/nokogiri-1.6.8/ext/nokogiri    [...]      Running 'compile' for libxml2 2.9.4... ERROR, review '/Users/me/.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/nokogiri-1.6.8/ext/nokogiri/tmp/x86_64-apple-da    rwin14.5.0/ports/libxml2/2.9.4/compile.log' to see what happened. Last lines are:    [...]     1 error generated.      make[2]: *** [xmlIO.lo] Error 1      make[1]: *** [all-recursive] Error 1      make: *** [all] Error 2      ========================================================================      *** extconf.rb failed ***      Could not create Makefile due to some reason, probably lack of necessary      libraries and/or headers.  Check the mkmf.log file for more details.  You may          need configuration options.    [...]        To see why this extension failed to compile, please check the mkmf.log which can be found here:          /Users/me/.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-14/2.3.0/nokogiri-1.6.8/mkmf.log          extconf failed, exit code 1  

And here's part of the mkmf.log file:

"gcc -o conftest -I/Users/me/.rvm/rubies/ruby-2.3.0/include/ruby-2.3.0/x86_64-darwin14 -I/Users/me/.rvm/rubies/ruby-2.3.0/include/ruby-2.3.0/ruby/backward -I/Users/me/.rvm/rubies/ruby-2.3.0/include/ruby-2.3.0 -I.  -I/usr/local/opt/libyaml/include -I/usr/local/opt/readline/include -I/usr/local/opt/libksba/include -I/usr/local/opt/openssl/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wshorten-64-to-32 -Wimplicit-function-declaration -Wdivision-by-zero -Wdeprecated-declarations -Wextra-tokens  -fno-common -pipe  conftest.c  -L. -L/Users/thanos/.rvm/rubies/ruby-2.3.0/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/readline/lib -L/usr/local/opt/libksba/lib -L/usr/local/opt/openssl/lib -L. -fstack-protector -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/readline/lib -L/usr/local/opt/libksba/lib -L/usr/local/opt/openssl/lib     -lruby.2.3.0  -lpthread -ldl -lobjc  "  /Users/me/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/mkmf.rb:395: warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777  checked program was:  /* begin */  1: #include "ruby.h"  2:  3: int main(int argc, char **argv)  4: {  5:   return 0;  6: }  /* end */  

I have no idea what is going on :(. Can someone help?

RUBY VERSION: 2.3.0p0. RUBYGEMS VERSION: 2.5.1

xcode-select is successfully installed.

Thanks!

Rails: which test method to use

Posted: 11 Jul 2016 07:52 AM PDT

I want to write some tests for my current project.

These tests will be mostly related to saved data in the database.

For example:

  • If a user registered 7 years ago, provide him gold badge (a boolean field set to true)

  • If registered 3 years ago then bronze badge etc.

Well, the calculations are bit more complicated before the boolean field is set to true. There are about 30-40 test cases that I need to test which are very similar to the above two examples.

I did some reading about Rails testing but I could not figure out the exact difference between integration, unit and functional testing in Rails.

In my case which testing method will be appropriate?

Changing checkbox icon with simple_form

Posted: 11 Jul 2016 08:37 AM PDT

I'm new at rails and web apps and I would appreciate if someone could help with this. Using simple_form and trying to change checkbox icon image but css(scss) seems not working. Codes are below.

<div class="col-md-6">     <%= f.input :is_something, as: :boolean, input_html: { class: 'custom-check-box' } %>  </div>  

And SCSS is

.custom-check-box {     opacity: 0;     vertical-align: middle;     input[type=checkbox] + label:after {       opacity: 1;       display: inline-block;       background: image-url('check_box_off.png');       background-repeat: no-repeat;       vertical-align: middle;       background-size: 50%;       cursor: pointer;       &:checked + label:after {         opacity: 1;         display: inline-block;         background-size: 50%;         background: image-url('check_box_on.png');         background-repeat: no-repeat;         vertical-align: middle;         cursor: pointer;       }     }   }  

how to get 3 week date information using specified date [duplicate]

Posted: 11 Jul 2016 07:04 AM PDT

This question already has an answer here:

i am using static day like monday,Tueday,friday and friday. how to get 3 week date after 3 week date..select specified day get 3 week date information. like select monday then get 11/07 , 18/07, 25/07

Does Postgres hav an equivalent of 'mysqldump --where'?

Posted: 11 Jul 2016 08:10 AM PDT

I'm working on a Rails project which uses the multi-tenanting gem Milia. Milia uses row-based tenanting, meaning that every row in the database has a column named tenant_id which determines who this data belongs to. We use Heroku and Postgresql.

The database as a whole is very large, and while there are times when I want the full production dump, much more often I would rather have only data for one tenant.

So then I'd like to dump the whole db, but only rows where tenant_id=x. mysqldump has a where condition, but I can't find an equivalent for Postgresql.

for example, if my database is like this:

Table Members    tenant_id, id, name, sex    1, 1, joe, m    1, 2, sally, f    2, 3, bob, m      Table Jobs    tenant_id, id  1, 1  1, 2  2, 3  

and I want to dump all the tables where tenant_id is 1, I would expect to get back a dump containing the following:

Table Members    tenant_id, id, name, sex    1, 1, joe, m    1, 2, sally, f      Table Jobs    tenant_id, id  1, 1  1, 2  

How select users where with paid is true and paid_subscriptions expirence_at current date?

Posted: 11 Jul 2016 07:44 AM PDT

I have model User

has_many: paid_subscriptions  

model PaidSubscription

belongs_to :user  

How me write active record query for select all users, where paid is true and paid_subscriptions expirence_at < current day?

EDIT:

User.includes(:paid_subscriptions).where("YEAR(created_at) = ? AND active = ?", 2011, true).where('paid_subscriptions.expirence_at < ?', Date.today)  

x-editable for bootstrap source selection

Posted: 11 Jul 2016 06:57 AM PDT

I have the following x-editable code working:

      <td>            <a href="#" class="xeditable" data-type="select" data-pk="1" data-emptytext="Assign" data-placement="right" data-resource="workorder" data-source="/employees.json?workgroup=<%= workorder.workgroup.id %>" data-name="employee_id" data-url="/workorders/<%= workorder.id %> " data-original-title="Select Employee">                  <% if workorder.employee_id != nil %>                      <%= workorder.employee.try(:employee_full_name) %>                  <% end %>             </a>        </td>  

I want to add ?archive=false to the data-source.

This didn't work:

data-source="/employees.json?archive=false?workgroup=<%= workorder.workgroup.id %>"  

How can I code this?

rails-jquery-autocomplete source being an array

Posted: 11 Jul 2016 08:15 AM PDT

I want to use rails jquery autocomplete but my source is a dynamic array from a field in my model. The documentation https://github.com/bigtunacan/rails-jquery-autocomplete only talks about the source being separate model instances. Is there a way to make it use an array and look at each array item as a separate object when querying the source?

autocomplete array = ["UBER US JUL01",                         "Transfer From PAYMENT/TRANSFER 010985 BA",                         "FANTASY SAIL & SIGN",                         "Fandango",                         "ANGEL'S RESTAURANT",                         "JEWEL"]  

Attempting to generate a URL from non-sanitized request parameters

Posted: 11 Jul 2016 06:23 AM PDT

I am getting this error when i try to use the code below,

link_to params.merge(:sort => column, :direction => direction, :page => nil) do        "#{title} #{content_tag(:i, "", class: "fa fa-chevron-#{direction == 'asc' ? 'up': 'down'}") }".html_safe      end  

specifically seems to happen when i add params.merge there. What is the real cause and what should i do?

full error message

Attempting to generate a URL from non-sanitized request parameters! An attacker can inject malicious data into the generated URL, such as changing the host. Whitelist and sanitize passed parameters to be secure.

using Rails version 5.

Rails Error: "\xE4" followed by "l" on UTF-8

Posted: 11 Jul 2016 06:43 AM PDT

When I load css or js files on rails 4.2.6 with the link tags javascript_include_tag and stylesheet_link_tag I get the error:

Encoding::InvalidByteSequenceError at /app "\xE4" followed by "l" on UTF-8

I never saw this error before. And when I load these same files with the html script like:

<script src="/assets/app/functions.js"></script>  

Then it works.

my app/assets/javascripts/application.js is:

//= require jquery  //= require jquery_ujs  //= require turbolink__s EDITED  //= require__tree .  EDITED  

Someone had this problem before?

Thanks!

Are these 2 lines of code the same ? JS vs Ruby

Posted: 11 Jul 2016 05:51 AM PDT

In ruby:

->  { 10.times {|i| puts i} }.call  

Javascript:

(function (){      for (i = 0; i<10; i++){          console.log(i);      }  })()  

Im coming from a JS background and something peaked my interest when learning about lambdas and Procs where it says that those are function without names which are called. That reminded me of the anonymous functions or IIFE in javascript.

Are these 2 examples the same? if not what is the difference ?

How to retrieve all related objects from a selection in Rails

Posted: 11 Jul 2016 08:34 AM PDT

In a Rails app I have two models which are related via has_many and belongs_to associations:

class Entity < ActiveRecord::Base    has_many :applicants  end  class Applicant < ActiveRecord::Base    belongs_to :entity  end  

Given a collection of Entity objects, how can I retrieve all of the related Applicant objects?

This works, but is very slow given a large selection:

# select some entities (in my app I'm using SearchKick to run the search)  entities = Entity.search params[:query]    # retrieve the applicants related to the selected entities  applicants = []  entities.each do |entity|    applicants += entity.applicants  end  

Is there a Rails short-hand to retrieve the Applicants related to the selected Entities?

Other things I've tried:

entities.class => Entity::ActiveRecord_Relation   entities.applicants => #error  entities.applicant_ids => #error  

How to query for the products belonging to category and sub categories the correct way

Posted: 11 Jul 2016 06:32 AM PDT

Categories and Sub categories are independent models. And each category will have all the sub categories.

While creating a product, the admin has to select a category and the sub category.

Following are the models I have come up with

class Product < ActiveRecord::Base      belongs_to :category  end    class Category < ActiveRecord::Base    has_many :products  end    class Sub < ActiveRecord::Base     has_many :products  end  

Here is the schema for the products

create_table "products", force: :cascade do |t|      t.string   "name"      t.integer  "price"      t.integer  "category_id"      t.integer  "sub_id"    end  

The product is created with something like this

Product.create(name: "Messi magnet custom",category_id: 1, sub_id: 2)  

And I am querying all the products that belong to a particular category and sub category like this

Product.where("category_id = ? AND sub_id = ?",9,3)  

Is there any thing wrong with the associations I am having? And anything I could do improve this?

Pry Debugger - ignore library code

Posted: 11 Jul 2016 05:44 AM PDT

is there an option to ignore standard rails libraries when using step into command in pry ruby debugger?

There is a lot of code in ActiveRecord/Rails that makes debugging almost impossible to run efficiently.

ActiveRecord::Base.connection.execute(sql).each not returning data

Posted: 11 Jul 2016 05:50 AM PDT

As part of an API application I am working on there is authentication required to make calls. I am attempting the most basic call with a curl command including the header basic authentication. In the authenticate block, which is called when a user attempts to access any secure calls, there is the following code:

unless credential = cache.fetch("credential::#{auth.credentials[0]}:#{Digest::MD5.hexdigest(auth.credentials[1])}")    sql = "SELECT * FROM credentials WHERE username = '#{auth.credentials[0]}' AND passwd_hashed = '#{Digest::MD5.hexdigest(auth.credentials[1])}'"    ActiveRecord::Base.connection.execute(sql).each do |row|      credential = row    end  end  

For some reason this is not returning any results. I have taken the sql outputted from this block and ran it in postgres where it returns the desired row. I have tested my environment to make sure I am connecting to the correct database which I am. Beyond that I am not sure what the problem is or how to diagnose it. Any help would be appreciated.

Any suggestions as to how I could return an error from this block would also help greatly. Tried adding exception handling but cant seem to get the syntax correct.

Organising data for a football (soccer) management simulation

Posted: 11 Jul 2016 05:49 AM PDT

I'm trying to create an online football (soccer) management game with Ruby on Rails, and as it's quite ambitious for me I'm finding some parts fairly challenging. I've coded a basic match engine, but when it comes to tactics, lineups, formations, etc. I'm finding it more difficult to organise the various data and create relations in ActiveRecord. The same applies to league and cup systems.

I'll try to provide a brief overview here:

  • a nation/club has a first team and a youth/u21 team
  • a nation/club/team has players
  • a nation/club/team has matches against others in league and cup systems
  • a league system has three leagues in each division (pyramid system: 1 promoted, 3 relegated)
  • a cup system has knockout matches (and occasionally mini-league group stages) including extra time and penalty shootouts
  • a league/cup has rounds/match days for each season
  • a round/match day has matches
  • a match has details e.g. scores/ratings
  • a match has actions e.g. goal/assist
  • a match has tactics/lineups for each team e.g. formation/players

Any ideas how best to organise this in models?

Accessing devise current_user inside another rails engine

Posted: 11 Jul 2016 05:23 AM PDT

So here is my issue. I have a main application which has devise in it,for which I am creating an engine. In the engine I need the current_user from main app. Not sure how I will get that, I tried this link but to no avail. Any help would be great. If this is not recommended please do explain why.

Can a github repo with gems that can't be bundled provide gems that can be bundled?

Posted: 11 Jul 2016 05:14 AM PDT

I have a Rails project where a private repository is used to provide several gems, as the bundler docs describe i.e. I have a block like

git 'https://github.com/someguy/private.git' do    gem 'a_nice_gem'    gem 'a_silly_gem'    gem 'a_much_needed_gem'  end  

in my Gemfile.

The repository, private.git, contains a gem bad_gem with an incorrectly formatted .gemspec, for instance, or bad dependencies. Bundling the project errors out, despite bad_gem not being a dependency.

Is there some way to make bundling my Rails app succeed without fixing bad_gem?

TypeError: $.url is not a function

Posted: 11 Jul 2016 05:09 AM PDT

I am having a javascript file named _report_js.html.erb file under app/views/reports. WHen I run my application, I am getting the error:

TypeError: $.url is not a function

This is my code:

<script type="text/javascript">      if($.url().param('ig') == 'true') {        alert("hi");        $('#icons').hide();        $('#photos').show();      end  </script>  

Formatting to_json method for child object

Posted: 11 Jul 2016 05:29 AM PDT

I have a Rails object Product:

{      id: 1      name: 'soup'  }  

And a Customer object:

{      id: 20      name: 'Ryans'  }  

They are linked via:

class Product < ActiveRecord::Base    belongs_to :customer  

When I call Product.to_json(methods: [:customer]), I get:

{      id: 1      name: 'soup',      customer: {          id: 20          name: 'Ryans'      }  }  

But I need this to be in the format:

{      id: 1      name: 'soup',      customer_name: 'Ryans'  }  

Is this possible? I'm using Rails v4.1.7

RoR rails_admin associate two models with drop-down to display options

Posted: 11 Jul 2016 05:00 AM PDT

sorry for my bad english.

I have two models "Blog, Categories", I want a blog has many categories, but it don't working, don't display in the form.

My files:

rails_admin.rb

RailsAdmin.config do |config|      config.model Blog do         edit do          field :title          field :body, :ck_editor          field :image do            thumb_method :large            end          field :categories          field :author, :hidden do            default_value do              bindings[:view].current_user.username            end          end        end       end      #config base#config for    config.actions do      dashboard                     # mandatory      index                         # mandatory      new      export      bulk_delete      show      edit      delete      show_in_app      end  end  

Blog.rb

class Blog < ActiveRecord::Base      has_many :categories, :as => :cat, :inverse_of => :cat        rails_admin do          field :categories      end      has_attached_file :image      validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/  end  

Categorie.rb

class Categorie < ActiveRecord::Base      belongs_to :cat, :polymorphic => true, :inverse_of => :categories  end  

I am newbie in RoR, please help, and thanks C:

TypeError: f.browser is undefined fancybox

Posted: 11 Jul 2016 06:07 AM PDT

I am facing error in my app/assets/javascripts/jquery/jquery.fancybox.pack.js file at this line:

5: (f.browser.msie?' allowtransparency="true"':"")+"></iframe>",error:'<p class="fancybox-error">The requested content cannot be loaded.<br/>  

At top of this file the version is mentioned as:

/*! fancyBox v2.1.0 fancyapps.com | fancyapps.com/fancybox/#license */  

I am using jquery-rails-3.1.4 and jquery-ui-rails-5.0.5 versions. Please help how can I get out of this error.

Hash Table Column Values as Integer

Posted: 11 Jul 2016 05:22 AM PDT

I have followed this tutorial to have a hash column on my model which works great.

When I work out codes in the rails console, it becomes different within my controller code. In the console:

Foo.update_attributes(bar: {"a" => 1, "b" => 2})  

My values are shown as an integer, in the console. In my controller, if I'm doing calculations, I have to add .to_i or .to_f and it becomes messy. My values will forever be a number. Can I simple add an int or float for the column?

add_column :foos, :bar, :hstore, :integer, default: {}, null: false  

The above does not work.

Find records with no has_many :through record matching criteria

Posted: 11 Jul 2016 06:06 AM PDT

Using Rails 4, and given the following models:

class Draft < ActiveRecord::Base    has_many :drafters    has_many :users, through: :drafters  end    class Drafter < ActiveRecord::Base    belongs_to :draft    belongs_to :user  end    class User < ActiveRecord::Base    has_many :drafters    has_many :drafts, through: :drafters  end  

How can I retrieve all Drafts which are not associated with the User instance current_user? That is, all Drafts d for which there is no Drafter belonging to d and current_user.

I have Squeel available if it helps.

fetch different keys with different attributes(params)

Posted: 11 Jul 2016 04:40 AM PDT

def appliance_params    params.require(:tv).permit(:x, y:, :z)  end  

In this example I receive a key 'tv' and the values x, y, and z.

How can I modify this function to receive different keys ?

This function can receive different appliances, I can receive a :iron, a :computer etc... with different values.

I will only receive one appliance in params.

wysihtml5: font size is not overriding earlier font sizes

Posted: 11 Jul 2016 04:36 AM PDT

I have written a small web-app where you can edit documents via the wysihtml5 Editor, like on this site: http://wysihtml.com.

after a few problems, quite everything worked fine, but now i recognized that when i change the font-size to 20 and put it back to 14 it still stays on font size 20 and both html-tags are used. Like this:

<span class="wysiwyg-font-size-20 wysiwyg-font-size-16">used font-size 20 at first, after i used 16, still stays on 20.</span>  

and it looks just a bit bigger than this:

used font-size 20 at first, after i used 16, still stays on 20.

Anyone a clue what it could be?

greetings

Login to facebook with status unknown (rails app)

Posted: 11 Jul 2016 04:37 AM PDT

view - "facebook_btn_login"

fb_log_man();

javascript - fb_log_man()

  console.log("fb_log_man");    FB.login(function(response){console.log("FB.LOGIN"); console.log(JSON.stringify(response));});    checkLoginState();  

javascript - checkLoginState()

function checkLoginState() {      var fb_params = {        status: "",        name: ""       };        FB.getLoginStatus(function(response) {        fb_params["status"] = statusChangeCallback(response);      });          if(fb_params["status"] == "connected") {          FB.api('/me', function(response) {            fb_params["name"] = response.name;            console.log(fb_params["name"]);            console.log(JSON.stringify(response));          });      }      console.log(fb_params);      renderLogin(fb_params);    }      function renderLogin(fb_params) {       $.ajax({        type: "POST",        url: "/facebook_login",         data: {fb_params},          success:function(data) {           console.log("SUCCESS POST");           console.log(data);           globalEval(data);         },         error:function(data) {           console.log("ERROR POST:");            console.log(data);           globalEval(data);         },         dataType: "html"      });      console.log("AFTER POST");    }  

When run application the status was "not_authorized" , then I successfully logged, then logged out and the status becomes "unknown". I can't log in with this status. How to log in again?

No comments:

Post a Comment