Sunday, April 17, 2016

How do I avoid "preflight requests"? | Fixed issues

How do I avoid "preflight requests"? | Fixed issues


How do I avoid "preflight requests"?

Posted: 17 Apr 2016 07:13 AM PDT

I am trying to get started with Ember Data and immediately ran into this problem were the browser sends a OPTIONS request before the actual request.

The development backend I am trying to communicate with is a rails 4.2 server running on my local machine (started with rails s -b 0.0.0.0 ) I currently use this api to communicate from both an android and an ios app. My end goal is to provide an Ember app in addition to the existing rails UI, but if I have to replace it and only have the Ember UI, that will be OK.

I did some reading on CORS and I think at at least understand what it is trying to do. If I understand correctly, the browser sees the Ember app as having been served by a server other than the one that requests are being made to and because of this asks the server if this is OK.

So my questions are:

  1. Will I be able to deploy my ember app to the real server such that these CORS OPTIONS requests are not needed? (ie, I assume a rails app can deliver an Ember app to the browser and the browser will see the source of the script as being the same as the target of the request and not require the prefight requests)
  2. How do I get this to work in development? I see there is a --proxy option on the ember s --proxy, which seemed like it was supposed to be the solution for this, but I have not been able to get it to work

When I navigate to the server url I am trying to access http://localhost:3000/api/v1/users rails logs the following response:

Started GET "/api/v1/users" for 127.0.0.1 at 2016-04-17 10:02:01 -0400  

Based on this, I think I have my Ember adapter set up correctly:

import JSONAdapter from 'ember-data/adapters/json-api';    export default JSONAdapter.extend({    host: 'http://127.0.0.1:3000',    namespace: 'api/v1'  });  

Then I start the Ember server with this command:

ember s --proxy http://127.0.0.1:3000  

The rails server is receiving the following request:

Started OPTIONS "/api/v1/users" for 127.0.0.1 at 2016-04-17 09:36:51 -0400  

Which fails because I don't have a route for that (and don't think I want to either).

saml call back url with devise

Posted: 17 Apr 2016 07:11 AM PDT

I have to authenticate user either by saml or by database credentials depending on how user wishes to get authenticated . I am stuck with two problems
1)I am receiving the saml response to the call back back url. I am not sure how to integrate it with devise.
2)I am not sure how to authenticate the user either by database or by saml response dynamically based on user choice.

Any suggestion would be really helpful

Date works in development but not production Rails MongoDB

Posted: 17 Apr 2016 07:10 AM PDT

I have a Coupon class and I want my app to check and see how many counts are left on the coupon and if the date for the coupon has expired. I have the following method in my class to check both of these.

Coupon class      def self.get(code)     where(      :code => (normalize_code(code)),      :$and => [        {         :$or => [           { :coupon_count.gte => 1  },           { :coupon_count    => nil }         ]       }, {         :$or => [           { :expires_at.gt => Time.now.utc },           { :expires_at    => nil      }        ]       }      ]    ).first   end  

This works fine in development when I enter a coupon. But in production it does not work. I use my MongoDB shell to create a coupon as follows.

db.Coupon.insert({code:'#COUPONNAME',discount_percent: 10, expires_at: new ISODate("2016-05-18"), coupon_count: 10, "description": '1st cold visit sign-up'})  

It seems that the problem is when the Coupon checks the expires_at date. In development it finds the coupon and works but in production it keeps not finding the coupon. Just for good measure here is my controller method for this.

charges_controller    @code = params[:couponCode]    if !@code.blank?    @coupon = Coupon.get(@code)      if @coupon.nil?      flash[:error] = 'Coupon code is not valid or expired.'      redirect_to new_managers_charge_path(id: @reportapproval.id)      return    elsif @coupon.discount_percent == 100      @reportapproval.report_paid = true      @reportapproval.free_coupon_used = true      @reportapproval.save!      @coupon.coupon_count = @coupon.coupon_count - 1      @coupon.save!      redirect_to managers_dashboard_path, :notice => "You have successfully requested a pre-paid report from #{@reportapproval.tenant_last_name} with a 'No-Pay' intro coupon."      return    else      @final_amount = @coupon.apply_discount(@amount.to_i)      @discount_amount = (@amount.to_i - @final_amount.to_i)    end  

Rails tag_id3v1 mp3

Posted: 17 Apr 2016 07:07 AM PDT

Rails 4.2 ap and taglib-ruby gem

I have tried a few approaches to tag my audio files using taglib-ruby.

I have tried as a carrierwave process, and now, I am trying to tag after_save.

My question, if I am doing a callback after_save:

 def tag_id3v1(tags)     TagLib::MPEG::File.open(file.path) do |file|     tag = file.id3v1_tag(true)     tag.title = :title     file.save  end  

end

what should my file path be? I have tried :file, :file_name, and the uploader version url, #{track.mp3.url}

I am trying to reopen the saved files and write the tags to the files. Does anyone have any hints on the best approach to do this?

Devise Token Auth :authenticate_user! works wrong

Posted: 17 Apr 2016 06:52 AM PDT

If I add before_action :authenticate_user! to ApplicationController, I get an error:

ActionView::Template::Error (undefined method `name' for nil:NilClass):      1: json.data @users, :name, :username  

What comes from this file:

show.jbuilder

json.data @users, :name, :username  

My controller:

users_controller.rb

class UsersController < ApplicationController      before_action :authenticate_user!      def show      @users = User.all        render 'users/show'    end    end  

If I remove before_action :authenticate_user! everything works just fine, I get JSON object with the list of users.

Why does it happen? Device usually returns 401, but devise_token_auth is trying to trigger my show and fails because can't access database. How to fix this weird behaviour?

Rails Heroku SocketError: getaddrinfo: Name or service not known

Posted: 17 Apr 2016 06:38 AM PDT

I am on a heroku app, Ruby 2.2.0, Rails 4.0.12 and using the geokit-rails gem.

When I do a IpGeocoder.geocode(request.remote_ip) I get the error:

Caught an error during Ip geocoding call: getaddrinfo: Name or service not known  

I searched online and found that the solution is to make an initialiser and require a library:

require 'resolv-replace'  

When I do so I get the error:

Caught an error during Ip geocoding call: Hostname not known: api.hostip.info  

I am not sure what I should do then. On my development machine works fine. Any clue what the issue is?

has_many relation implicit conversion error after upgrading ruby and rails version

Posted: 17 Apr 2016 07:24 AM PDT

I have just upgraded my ruby on rails project

ruby 1.9.3-p551 to ruby 2.3.0

and

rails 3.2.13 to rails 3.2.22 (3-2-stable)

There were no errors prior to the upgrade.

In my user model I have some complex relationships in order to manage a user's contacts, and when accessing these relations I am getting a no implicit conversion of nil into String error.

The relationships are defined as -

has_many :contacts, :foreign_key => 'owner_id'  has_many :pending_invited, conditions: {:'contacts.confirmed' => false, :'contacts.denied' => false }, through: :contacts, class_name: 'User', source: :user  has_many :invited, conditions: { :'contacts.confirmed' => true }, through: :contacts, class_name: 'User', source: :user    has_many :inverse_contacts, :foreign_key => 'user_id', :class_name => 'Contact'  has_many :pending_invited_by, conditions: {:'contacts.confirmed' => false, :'contacts.denied' => false }, through: :inverse_contacts, class_name: 'User', source: :owner  has_many :invited_by, conditions: {:'contacts.confirmed' => true }, through: :inverse_contacts, class_name: 'User', source: :owner    has_many :denied, conditions: {:'contacts.denied' => true }, through: :contacts, class_name: 'User', source: :user  has_many :denied_by, conditions: {:'contacts.denied' => true }, through: :inverse_contacts, class_name: 'User', source: :owner  

Using rails c I am able to get a full stack trace by running -

u = User.first  u.pending_invited_by  

and this produces the following error -

TypeError: no implicit conversion of nil into String      from .bundle/gems/arel-3.0.3/lib/arel.rb:40:in `initialize'      from .bundle/gems/arel-3.0.3/lib/arel.rb:40:in `new'      from .bundle/gems/arel-3.0.3/lib/arel.rb:40:in `sql'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/join_helper.rb:47:in `block in sanitize'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/join_helper.rb:45:in `map'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/join_helper.rb:45:in `sanitize'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/association_scope.rb:94:in `block in add_constraints'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/association_scope.rb:39:in `each'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/association_scope.rb:39:in `each_with_index'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/association_scope.rb:39:in `add_constraints'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/association_scope.rb:31:in `scope'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/association.rb:99:in `association_scope'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/association.rb:88:in `scoped'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/has_many_through_association.rb:178:in `find_target'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/collection_association.rb:335:in `load_target'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/collection_proxy.rb:44:in `load_target'      from .bundle/bundler/gems/rails-f85bbed4cdc1/activerecord/lib/active_record/associations/collection_proxy.rb:89:in `method_missing'      from .bundle/bundler/gems/rails-f85bbed4cdc1/railties/lib/rails/commands/console.rb:47:in `start'      from .bundle/bundler/gems/rails-f85bbed4cdc1/railties/lib/rails/commands/console.rb:8:in `start'      from .bundle/bundler/gems/rails-f85bbed4cdc1/railties/lib/rails/commands.rb:41:in `<top (required)>'      from script/rails:6:in `require'  

Any help is appreciated.

Redirection using API call

Posted: 17 Apr 2016 06:19 AM PDT

My rails app is consuming an API, for which I auto submit a form and redirect to another website. I am doing it as below:

  <%= form_tag "https://www.<somewebsite>.action", method: :post,:protocol => 'https',:id => 'test' do %>      <%= hidden_field_tag 'field1', 'value1' %>       <%= hidden_field_tag 'field2', 'value2' %>            <%= hidden_field_tag 'field3', 'value3' %>        <% end %>     <script>document.getElementById('test').submit();</script>  

This works and opens the other website in another window. Is it by any chance possible to call this redirection in an "iframe" so that the url of the other website is masked. I don't want the user to know that he/she is being redirected to another website.

Rails & Ajax: display products by chosen filters

Posted: 17 Apr 2016 05:25 AM PDT

I need to display products by chosen categories using Ajax; if the user didn't choose a category, then all the products are displayed. If the user chose one or two categories, then only products that belong to these categories should be displayed.

Example:

enter image description here

My models Product, Category, and join table causes_products

Category

class Category < ActiveRecord::Base has_and_belongs_to_many :products end

Products

class Product < ActiveRecord::Base has_and_belongs_to_many :categories end


I was looking for a tutorial and I found "Rails 4: "How to partials & AJAX, dead easy". I followed this tutorial but I got an error. I feel like I missed something.
Can you please advise me on this or refer to a helpful source. Thank you!

products controller:

class ProductsController < ApplicationController    def index      @products = Product.all      @categories = Category.all    end    def from_category      @selected = Product.where(:category_id => params[:cat_id])      respond_to do |format|        format.js      end    end  end  


products/index.html.erb:

<div class="grid">    <%= render 'sidebar_menu' %>    <%= render partial: 'product_grid', locals: { products: @products} %>  </div>  


products/_sidebar_menu

<% @categories.each do | cat | %>  <%= link_to cat.name, fetch_products_path(:cat_id => cat.id), :remote => true %>  <% end %>  


routes.rb

get "/fetch_products" => 'products#from_category', as: 'fetch_products'  


products/_products_grid.html.erb

<div>    <%= render partial: 'products_list', locals: { products: products } %>  </div>  


products/_products_list.html.erb

<% products.each do |product| %>      <div class="product_box">        product.name      </div>  <% end %>  


products/from_category.js.erb

$("#products_grid").html("<%= escape_javascript(render partial: 'products_list', locals: { products: @selected } ) %>");  


my terminal output:

Product Load (3.2ms)  SELECT `products`.* FROM `products` WHERE `products`.`category_id` = '11'  Mysql2::Error: Unknown column 'products.category_id' in 'where clause': SELECT `products`.* FROM `products` WHERE `products`.`category_id` = '11'      Rendered products/_products_list.html.erb (8.8ms)      Rendered products/from_category.js.erb (12.2ms)      Completed 500 Internal Server Error in 23ms (ActiveRecord: 3.5ms)      ActionView::Template::Error (Mysql2::Error: Unknown column 'products.category_id' in 'where clause': SELECT `products`.* FROM `products` WHERE `products`.`category_id` = '11'):      1: <% products.each do |product| %>      2:     <div class="product_box">      3:     <%= product.name %>      4:     </div>    app/views/products/_products_list.html.erb:1:in `_app_views_products__products_list_html_erb___255698018512654633_70336949043820'    app/views/products/from_category.js.erb:1:in `_app_views_products_from_category_js_erb___4172137050793767106_70336965664480'    app/controllers/products_controller.rb:24:in `from_category'`  




* - originally sidebar_menu file contained only one line:
<%= link_to cat.name, fetch_items_path(:cat_id => cat.id), :remote => true %>
but I got this error:

Showing views/products/_sidebar_menu.html.erb where line #1 raised:    undefined local variable or method `cat' for #<#<Class:0x007ff1336747c0>:0x007ff1350376a8>  Extracted source (around line #1):    <%= link_to cat.name, fetch_products_path(:cat_id => cat.id), :remote  => true %>  

Devise authentication with Angular2

Posted: 17 Apr 2016 05:05 AM PDT

I have an Angular2 application which is supposed to work with Rails 5 beta 3 API. This API uses gem 'devise', '~> 4.0.0.rc2' for authentication. In Angular app I have a LoginService a function that sends a POST request to /users/sign_in.json which is handled by Devise::SessionsController.

Angular: login.service.ts

import {Injectable} from 'angular2/core';  import {Headers, RequestOptions} from 'angular2/http';  import {Observable} from "rxjs/Observable";  import {User} from "./../user";  import {Http, Response} from 'angular2/http';    @Injectable()    export class LoginService {        constructor (private http: Http) {}        private _user_session_url = '/users/sign_in.json';        login (username: string, password: string) : Observable<User> {          let body = JSON.stringify({ user: {username: username, password: password} });          let headers = new Headers({ 'Content-Type': 'application/json' });          let options = new RequestOptions({ headers: headers});            return this.http.post(this._user_session_url, body, options).map((data: any) => data.json()).catch(this.handleError)      }        private handleError (error: Response) {          return Observable.throw(error.json().error || 'Server error');      }  }  

But here is what happenes on my server when I send this request.

Started POST "/users/sign_in.json" for 127.0.0.1 at 2016-04-17 14:51:22 +0300

Processing by SessionsController#create as JSON    Parameters: {"user"=>{"username"=>"demo", "password"=>"[FILTERED]"}, "session"=>{"user"=>{"username"=>"demo", "password"=>"[FILTERED]"}}}    User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."username" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["username", "demo"], ["LIMIT", 1]]     (0.2ms)  BEGIN    SQL (0.5ms)  UPDATE "users" SET "current_sign_in_at" = $1, "last_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "users"."id" = $5  [["current_sign_in_at", 2016-04-17 11:51:22 UTC], ["last_sign_in_at", 2016-04-17 11:46:51 UTC], ["sign_in_count", 16], ["updated_at", 2016-04-17 11:51:22 UTC], ["id", 4]]     (0.9ms)  COMMIT    Rendered sessions/create.jbuilder (0.3ms)  Completed 200 OK in 142ms (Views: 0.9ms | ActiveRecord: 2.1ms)      Started GET "/messages.json" for 127.0.0.1 at 2016-04-17 14:51:35 +0300  Processing by MessagesController#show as JSON  Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms)  

So, what basically happens is authentication goes well, but but then on the page refresh I'm still unauthorized. As I understand, the problem is in lack of CSRF token. So my questions are:

  • How do I get a CSRF token in my Angular app?
  • How can I return Devise errors as JSON?

illegal hardware instruction on installing backup from retina 2014 to non-retina 2011

Posted: 17 Apr 2016 04:14 AM PDT

recently i have installed my backup from macbook pro mid-2014 retina to a macbook pro late-2011 non-retina, after that i'm trying to run rails server or any ruby related commands like (rake, rake "tasks", ... etc) repeatedly get the following 71035 illegal hardware instruction rails s the number and the commands changes but the same illegal hardware output, i uninstalled ruby and reinstalled it using rvm but the same illegal hardware instruction output still the same.

any help would be appreciated, thanks in advance.

Instagram API bad request : Please supply a valid action from the following: follow, unfollow, approve, ignore, block, unblock

Posted: 17 Apr 2016 04:18 AM PDT

I can't manage to send the action "follow" as postdata when I'm doing a POST request to the Instagram API. I'm trying to make a button_to in my rails app.

Here is the erb code :

<%= button_to "Follow", "https://api.instagram.com/v1/users/*[user_id]*/relationship?access_token=*[token]*", data: {action: "follow"} %>  

The by default method for Button_to is POST so I don't need to specify that. And I have to send the "follow" action in the request body, but I don't see how.

Any help ?

Rails low level query caching

Posted: 17 Apr 2016 05:40 AM PDT

I would like to cache a controller query result because it's a very static data which wont change very often.

So I am wondering if I can just define this method:

  def cached_collections      Rails.cache.fetch('collections', :expires_in => 24.hours) do        Collection.all      end    end  

And in some way instead using

@collections = Collection.all  

can I just call the method?

@collections = cached_collections  

This is working but it's the right way to do it? before using Memcached or Redis

Couldn't find file 'jquery-ui/datepicker' [duplicate]

Posted: 17 Apr 2016 05:18 AM PDT

This question already has an answer here:

Version Rails 5 beta 3. I am using gem jquery-ui-rails 5.0.5

gemfile

group :assets do     # Use SCSS for stylesheets    gem 'sass-rails', '~> 5.0'    # Use Uglifier as compressor for JavaScript assets    gem 'uglifier', '>= 1.3.0'    # Use CoffeeScript for .coffee assets and views    gem 'coffee-rails', '~> 4.1.0'    gem 'jquery-ui-rails'    end  

application.js:

//= require turbolinks  //= require jquery  //= require jquery-ui/datepicker  //= require jquery_ujs  //= require jquery.turbolinks  //= require cocoon  //= require jquery_nested_form  //= require jquery-fileupload/basic  

application.css

/**   * application.css   *   *= require jquery-ui/datepicker   *= require_self   *= require_tree ./all  */  

I installed all gems, restarted server, run project and displaying error: couldn't find file 'jquery-ui/datepicker' with type 'text/css'

Help, please.

Dynamically add method in before(:all)

Posted: 17 Apr 2016 03:36 AM PDT

Im testing a Module that can be included in a Controller. Right now the code looks like that:

class GithubAuthorizationController < ApplicationController    include Frontend::Concerns::GithubAuthorization      def index      render inline: "lorem_ipsum"    end  end    describe GithubAuthorizationController do    before(:all) do      @page_content = "lorem_ipsum"    end    ...........  

As you can see I basically create a Test-Controller before the tests are run. Now I would like to add the module and index method in the before(:all)-block. I tried:

class GithubAuthorizationController < ApplicationController  end    describe GithubAuthorizationController do    before(:all) do      @page_content = "lorem_ipsum"        class < @controller        include Frontend::Concerns::GithubAuthorization          def index          render inline: "lorem_ipsum"        end      end    end    ...........  

As I can see in debugger in the before(:all) block the @controller is defined as <GithubAuthorizationController .... So It is a instance. There Is also no error when running the code, but the tests fails, because of The action 'index' could not be found ...

What do I wrong? How can I move the code to the before(:all) block? Thanks

Importing csv. data to a new mysql table

Posted: 17 Apr 2016 06:01 AM PDT

i got the problem of importing multiple .csv files with user generated names.

I already got the import method but with no particular filename to create a new table which name is chosen by the user. Right now it works like this:

index.html.erb:

Upload new Files:          <%= form_tag import_requests_path, multipart: true do %>              <%= file_field_tag :file %>              <input type="text" id="file_name" placeholder="Please insert Filename" >              <%=submit_tag "Upload" %>          <%end%>  

routes.rb:

resource :requests do      collection { post :import}    end  

requests_controller.rb

def import          Request.import(params[:file])          redirect_to welcome_index_path      end  

request.rb:

def self.import(file)          CSV.foreach(file.path, headers: true) do |row|              Request.create! row.to_hash          end      end  

What I want to do right now is:
Let the user choose a Filename in the index.html.erb in the form_tag. This should be send to the import method with its ID and after this create a new mysql table with the chosen name. It is planed to choose all the created tables from a tag in the index.html.erb file.

Rails loop, link_to model_view

Posted: 17 Apr 2016 02:26 AM PDT

Rails: Need help looping through model array to link to the show page. I want to show the name, but link to the path. Seems like it should be simple but I have been coding all night and my brain is fried! please help.

      <div class="container">            <div class="row">             <% @bars.each do |bar| %>              <div class="col-xs-6 something">                <div class="firstBar">                  <%= link_to bars_path %>                  <% end %>                </div>              </div>            </div>          </div>  

How can I make the font awesome spinner icon to show up?

Posted: 17 Apr 2016 02:18 AM PDT

All the animation works except that the spinning icon is not visible.

<%= f.button :button, "Sign up".html_safe, class: 'btn btn-primary', data: {disable_with: "<i class='fa fa-spinner fa-spin'></i> Signing up..."} %>  

How can I permit array in rails post request

Posted: 17 Apr 2016 02:18 AM PDT

Hey I am trying permit these parameters in rails create controller . I am using a ajax post request to send an array as a params . But I am unable to access it in rails controller . How can I permit this and show it in json as a response .

 Parameters: {"combination_dose"=>{"shared_items"=>{"0"=>{"entity_id"=>"253", "position"=>"1"}, "1"=>{"entity_id"=>"823", "position"=>"2"}}}}  

Missing secret token even if it is set on environment variable

Posted: 17 Apr 2016 03:40 AM PDT

I have generated locally secret key by running this command:

rake secret  

Then in my Ubuntu VPS I have created environment variable like this:

echo 'export SECRET_KEY_BASE=<locally_generated_secret_string>' >> ~/.bashrc  

Then I have realoaded my bashrc by running this:

source ~/.bashrc  

When I type echo $SECRET_KEY_BASE it outputs to me this generated string

Then I have uploaded my rails app via capistrano and launched it. However, logs still shows this error message:

#<RuntimeError: Missing `secret_token` and `secret_key_base` for 'production' environment, set these values in `config/secrets.yml`>  

Why this is happening?

Rails asset precompiling

Posted: 17 Apr 2016 01:32 AM PDT

I am trying to set up Rails 5 with bootstrap-sass.

app/assets/application.scss:

@import "bootstrap-sprockets";  @import "bootstrap";  

config/initializers/assets.rb:

Rails.application.config.assets.version = '1.0'  Rails.application.config.assets.precompile += %w(*.js *.css)  

I get following error: Sass::SyntaxError ... Undefined variable: "$alert-padding". This is because of *.css in precompile.

But if I leave only %w(*.js) Rails will still compile my controller specific stylesheets. I am happy because it will but why will it do this?

Two separate has_many tables

Posted: 17 Apr 2016 03:15 AM PDT

I am having trouble pulling the data I need using two separate many to many associated tables.

   class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable      has_many :meals    has_many :lists  end    class Meal < ActiveRecord::Base    belongs_to :user    has_many :meal_lists    has_many :lists, through: :meal_lists    has_many :meal_ingredients    has_many :ingredients, through: :meal_ingredients  end    class List < ActiveRecord::Base    has_many :meal_lists    has_many :meals, through: :meal_lists    belongs_to :user  end    class MealList < ActiveRecord::Base    belongs_to :meal    belongs_to :list  end  

My end result is to be able to pull out all the meals that are both associated with the list_id and the user_id.

So far I have tried

@list = @user.lists.create("name: "users list")  list.meals.create(name:"List name", user_id: user.id)  list.meals.where(user_id: user.id)  

I can not seem to figure out how to pull out the meals that are both associated with the user_id and the list_id.

EDIT: After reading the first answer here is how I interpreted how to implement it. Keep in mind I am still at the beginning of learning rails and I've been staring at this problem for hours and the more I stare the more obscure it seems.

I created a method within the model:

Class List < ActiveRecord::Base      def self.find_user_meals(user, list)      meal = Meal.joins(:meal_lists)      user_meal = meal.where(user: user)      list_meal = user_meal.where(meal_lists: { list: list } )      return list_meal.distinct    end  end  

and within my controller:

def edit      @list = List.find(params[:id])      user = current_user      @meals = Meal.all      @all_user_meals = List.find_user_meals(user, @list)    end  

And in the view I just iterate over @all_user_meals. I read a little bit into joins and includes after the first answer and seemed to get something to work somewhat within the console. This is not quite working in the app, and I am just trying to wrap my head around it a little bit better.

DOUBLE EDIT:

So I guess I was just tired and overthinking the problem. What I didn't realize was that the lists are created by one user so I was able to solve this fairly simply.

def edit      @list = List.find(params[:id])      user = current_user      @meals = Meal.all.where(user_id: user.id)      @listed_meals = @list.meals    end  

I can't believe how much time I spent on this. Thanks for spending the time looking at this. Sometimes associations confuse me, other times they seem straightforward.

Prevent duplicated code

Posted: 17 Apr 2016 12:53 AM PDT

I have this test:

    it "redirects him to vice" do        get :show        uri_request_1 = Addressable::URI.parse(response.redirect_url)        redirects_to_vice_1 = uri_request_1.host == "vice.com"          get :show, relative_path: "/Fun/Facts.html"        uri_request_2 = Addressable::URI.parse(response.redirect_url)        redirects_to_vice_2 = uri_request_1.host == "vice.com"          assert redirects_to_vice_1 && redirects_to_vice_2      end  

It has a lot of repetition. How can I shorten this test?

NoMethodError undefined method `persisted?' for nil:NilClass when signing in with Facebook thru Omniauth/Devise?

Posted: 17 Apr 2016 01:36 AM PDT

I am putting the finishing touches on a Rails app, and everything was working fine just yesterday, (most of it still is). But now, when I try to sign in with Facebook I get the error NoMethodError undefined method persisted? for nil:NilClass I haven't changed any code in the omniauth_callbacks_controller, or in the User Model, so I do not understand why this is happening all of the sudden.

Here's the code in omniauth_callbacks_controller

def self.provides_callback_for(provider)  class_eval %Q{    def #{provider}      @user = User.from_omniauth(env["omniauth.auth"])        if @user.persisted?        sign_in_and_redirect @user, event: :authentication        set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format?      else        session["devise.#{provider}_data"] = env["omniauth.auth"]        redirect_to new_user_registration_url      end    end  }  end    [:twitter, :facebook].each do |provider|  provides_callback_for provider  end  

And in User.rb

def self.from_omniauth(auth)  identity = Identity.where(provider: auth.provider, uid: auth.uid).first_or_create do |identity|    if identity.user == nil      user = User.new      user.email = auth.info.email || "#{auth.uid}@#{auth.provider}.generated"      user.password = Devise.friendly_token[0,20]      user.provider = auth.provider      if auth.provider == "facebook"        user.name = auth.info.name        user.username = "FacebookUser" + (1 + rand(1000)).to_s      elsif auth.provider == "twitter"        user.name = auth.info.name        user.username = auth.info.nickname      end    end    identity.user = user  end    identity.access_token = auth['credentials']['token']  identity.refresh_token = auth['credentials']['refresh_token']  identity.expires_at = auth['credentials']['expires_at']  identity.timezone = auth['info']['timezone']  identity.save  identity.user  end  

I cannot figure out why it WAS working yesterday, but now it's not. Nothing has changed! I'm still accessing it from the same URL, I haven't messed with the API settings on Facebook, or in devise.rb.

Having different associations between two models Rails

Posted: 17 Apr 2016 12:24 AM PDT

I am building an event app that lets users post events, and other users can 'register' themselves as attending that event. I currently have two models, 'User' and 'Article', where article is the event that a user can post. An article belongs_to :user and a user has_many :articles, dependent: :destroy.

I am trying to set up a new database to store which users plan to attend an event, in the form of a 'Registration', where it stores a user and the event he plans to attend. This means i need a many to many association between Users and Articles (as a user can attend multiple events, and an event can have multiple attendees). But will this not conflict with the original setting that states an article belongs to a single user?

How do i set this up so my associations dont interfere?

Change the mail id on aws after verification and use that mail id to send mails using SMTP

Posted: 16 Apr 2016 11:46 PM PDT

I want to change mail id through which i want to send mails using smtp and application hosting is on aws.

My production.rb looks like:

config.action_mailer.delivery_method = :smtp    config.action_mailer.default_url_options = { host: Host IP}    config.action_mailer.smtp_settings = {        :address => 'email-smtp.us-east-1.amazonaws.com',        :user_name => username,        :password => password,        :authentication => :login,        :enable_starttls_auto => true    }  

devise_mailer.rb looks like:

class DeviseMailer < Devise::Mailer    address = Rails.env == 'production'? 'support@domain' : '*****@domain'      default from: address, reply_to: address  end  

aws verified email

Email Feedback Forwarding:enabled     DKIM Settings Generated:yes  Bounce Notifications SNS Topic:none   DKIM Verification Status:failure  Complaint Notifications SNS Topic:none    DKIM Signing:verification attempts failed  Delivery Notifications SNS Topic:none     MAIL FROM Domain:amazonses.com  

And i am getting error although my email id is verified. Net::SMTPFatalError (554 Message rejected: Email address is not verified. ): Please help me and tell me if i am wrong somewhere.

Rails 4 Set Value of the logged in User by default before create

Posted: 16 Apr 2016 11:58 PM PDT

I have the following models

members (id, name, company_id..)  companies (id, name, ...)  campaigns (id, company_id, ...)  

When creating a Campaign i have the following

def create      @campaign = Campaign.new(campaign_params)      if @campaign.save        redirect_to campaigns_path(@campaign)      else        render :new      end    end  

i have a helper method from the AppController called current_company whose id i want to set to @campagin.company_id

which is the best way to set the default logged in users company.id to every campaign created?

can i traverse through current_company and build a query like this?

@campaign = current_company.campaign.new(campaign_params)  

Could not find rake

Posted: 16 Apr 2016 11:20 PM PDT

I use rvm and current default ruby version is 2.3.0. rvm list output:

ruby-2.2.1 [ x86_64 ]
=* ruby-2.3.0 [ x86_64 ]

But the search is coming from /home/ninjavalerok/**.rvm/gems/ruby-2.2.1**@global/gems/bundler-1.8.4/lib/bundler. How can I configure the search path? Because I think that the problem is there.

Full error output:

Error:[rake --tasks] /home/ninjavalerok/.rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/spec_set.rb:92:in block in materialize': Could not find rake-11.1.2 in any of the sources (Bundler::GemNotFound) from /home/ninjavalerok/.rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/spec_set.rb:85:in map!' from /home/ninjavalerok/.rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/spec_set.rb:85:in materialize' from /home/ninjavalerok/.rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/definition.rb:132:in specs' from /home/ninjavalerok/.rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/definition.rb:177:in specs_for' from /home/ninjavalerok/.rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/definition.rb:166:in requested_specs' from /home/ninjavalerok/.rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/environment.rb:18:in requested_specs' from /home/ninjavalerok/.rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/runtime.rb:13:in setup' from /home/ninjavalerok/.rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler.rb:122:in setup' from /home/ninjavalerok/.rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/setup.rb:18:in ' from /home/ninjavalerok/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in require' from /home/ninjavalerok/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:inrequire'

Rails 4: Integrating Disqus

Posted: 17 Apr 2016 12:46 AM PDT

I'm trying to figure out how to use the disqus-rails gem in my Rails 4 app. https://github.com/sandric/disqus_rails

The instructions say to include an access token in an initialiser. I can't figure out how to generate an access token. I have setup my app and channel in disqus, but can't find the token.

Where do I go to get the access token for disqus?

Devise update_without_password gives ForbiddenAttributesError

Posted: 16 Apr 2016 11:18 PM PDT

I added additional fields to my user model, then updated the configure_account_update_params method accordingly. Everything was working until I wanted users to be able to update their information without having to input their current password.

So I removed the field for the view and changed the update method in the RegistrationsController

This is my controller, I'm not sure if I'm missing something

class Users::RegistrationsController < Devise::RegistrationsController    before_filter :configure_account_update_params, only: [:update]      def update      resource.update_without_password(resource_params)    end      # If you have extra params to permit, append them to the sanitizer.    def configure_account_update_params      devise_parameter_sanitizer.for(:account_update) << [:first_name, :last_name, :country, :phone_number, :gender, :birthdate]    end  end  

No comments:

Post a Comment