Monday, April 4, 2016

Add custom response header with Rack-cors and Grape | Fixed issues

Add custom response header with Rack-cors and Grape | Fixed issues


Add custom response header with Rack-cors and Grape

Posted: 04 Apr 2016 08:31 AM PDT

I'm developing a Ionic(Cordova) app with a Ruby on Rails API. I want to use response headers to return a token after login. I'm using rack-cors gem to make Cross Origin Request work:

application.rb

config.middleware.insert_after Rails::Rack::Logger, Rack::Cors, :logger => Rails.logger do        allow do          origins '*'          resource '/api/*', :headers => :any, :methods => [:get, :post, :options, :put]        end      end  

and grape gem to manage my API routes. But i can't find a way to add a header to my response since i added rack-cors.

I tried this:

header('Access-Token', user.token.key)  

But it doesn't work. Whatever i do i end up with those headers:

{cache-control: "max-age=0, private, must-revalidate", content-type: "application/json"}

Can anyone help me with this issue ?

Execute Javascript when rendering .html.erb partial

Posted: 04 Apr 2016 08:20 AM PDT

I have a post model and a step model. A post has_many steps. On my form to create a new post, I have a button that dynamically appends a form to create a step. To do this, I render a partial onClick of this button.

In this partial, there is some javascript in a script tag, that does a few things in the step's form.

However, on the /edit page of the post, the steps that were already created appear but don't have the behavior that the Javascript should create.

I have this in my post form:

<% @post.steps.each do |step| %>    <%= render 'steps/step_form', step: step %>  <% end %>  

And in the partial, at the bottom I have:

<%= render 'steps/step_form_js.js.erb', step: step %>  

But the last render displays the javascript code in the page.

How can I execute the javascript code on the edit form for each step ?

Sendgrid inbound parsing url API within rails

Posted: 04 Apr 2016 08:18 AM PDT

While there are many questions and answers on sendgrid inbound parsing configuration in this site, I could not find answer to my specific problem.

In my SAAS app each customer can setup there own subdomain and also receive emails. I see that sendgrid provides API to create webhoooks with an api. How to accomplish this programicaly within rails? Documentation is here.

https://sendgrid.com/docs/API_Reference/Web_API/parse_settings.html

Thanks for your help.

Dealing with Time.now in Rails console

Posted: 04 Apr 2016 08:21 AM PDT

I have a Message model and it has a send_at attribute that logs the time it was sent. In the console I'm trying to find the messages that are set for the future. Now I'm putting in the command Message.where(send_at: < Time.now) This is getting an error and I really didn't expect it to work. Does anybody know what the proper command would be for this query.

ActiveRecord OR query (multiple conditions)

Posted: 04 Apr 2016 08:19 AM PDT

How do I create an ActiveRecord query without using a SQL string in Rails to get something like:

books = Book.where(author: 1, from_day: [1,5] or to_day: [1,5])

Ruby Selenium / Page Object Model - launching Browser

Posted: 04 Apr 2016 08:05 AM PDT

I'm learning selenium web-driver with ruby and page object model. My test code is below:

When I run the test I get an error unable to locate element which is due to the page loading but not redirecting to the correct link. Usually I would use driver.gets but cant get it to work with page object model?

require 'rubygems'  require 'selenium-webdriver'  require 'page-object'          class ContactDemoQa    include PageObject        text_field(:name, :css => '#wpcf7-f375-p28-o1 > form > p:nth-child(2) > span > input')  text_field(:email, :css => '#wpcf7-f375-p28-o1 > form > p:nth-child(3) > span > input')  text_field(:subject, :css => '#wpcf7-f375-p28-o1 > form > p:nth-child(4) > span > input')  text_area(:messages, :css => '#wpcf7-f375-p28-o1 > form > p:nth-child(5) > span > textarea')    button(:send, :css => '#wpcf7-f375-p28-o1 > form > p:nth-child(6) > input')        def contact_method(name, email, subject, message)        self.name = name      self.email = email      self.subject = subject      self.message = message      send    end    browser = 'http://demoqa.com/contact/'    browser = Selenium::WebDriver.for :firefox    contact_demo_qa = ContactDemoQa.new(browser)      contact_demo_qa.contact_method 'rob', 'green@hotmail.co.uk', 'test', 'Yellow'    end  

With Page object model are you meant to have Page objects and methods in one class and then call the method using code below in another class?

browser = 'http://demoqa.com/contact/'    browser = Selenium::WebDriver.for :firefox    contact_demo_qa = ContactDemoQa.new(browser)      contact_demo_qa.contact_method 'rob', 'green@hotmail.co.uk', 'test', 'Yellow'  

Jquery Chosen Plugin with Materializecss Design

Posted: 04 Apr 2016 07:39 AM PDT

Anybody has any clue about using jquery chosen plugin with materializecss design.

pagination with kaminari and mongoid

Posted: 04 Apr 2016 07:13 AM PDT

I have this problem

undefined method `total_pages' for #<Mongoid::Criteria:0x00000002651d80>

Controler

@services = Service.paginate(:page => params[:page], :per_page => 3)

view

<% paginate @services %>

The mongo dont return the object.

Nested forms rails field does not update

Posted: 04 Apr 2016 07:15 AM PDT

I am trying to do nested forms like mentioned here. http://guides.rubyonrails.org/form_helpers.html#nested-forms

The goal is as follows: I have multiple colli with one checkbox which can be checked. The colli list can be deleted or modified but the checks and their information need to stay.

Model

class Colli < ActiveRecord::Base    has_one :check, foreign_key: "subcontainerid", primary_key: "colliid"    accepts_nested_attributes_for :check, allow_destroy: true  end    class Check < ActiveRecord::Base    belongs_to :colli  end  

So every colli has one check. The colliid from the colli table created a link with the check table using the subcontainer id.

Controller

Within the colli controller I whitelist the check_attributes.

def colli_params    params.require(:colli).permit(:colliid, :collinaam, check_attributes: [:id, :checked])  end  

Form

My form looks like this.

<%= form_for(@colli) do |f| %>    <% if @colli.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@colli.errors.count, "error") %> prohibited this colli from being saved:</h2>          <ul>        <% @colli.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>      <%= f.fields_for :checks do |checks_f| %>    <p>check start</p>    <div class="field">      <%= checks_f.label :checked %><br>      <%= checks_f.check_box :checked %>    </div>    <% end %>      <div class="field">      <%= f.label :colliid %><br>      <%= f.text_field :colliid %>    </div>      <div class="field">      <%= f.label :collinaam %><br>      <%= f.text_field :collinaam %>    </div>      <div class="actions">      <%= f.submit %>    </div>    <% end %>  

If I do form_for :check I can't see the checkboxes. When I do form_for :checks I see a checkbox but it does not work. When clicking submit I see following error:

undefined method `checked' for nil:NilClass    <p>    <strong>Checked:</strong>    <%= @colli.check.checked %>  </p><p>    <strong>Collinaam:</strong>    <%= @colli.collinaam %>  

Which means it did not get saved. Does anybody know how to fix this?

ruby version on remote server is not changed

Posted: 04 Apr 2016 08:33 AM PDT

This is about configuring remote Ubuntu server through SSH utility for hosting Ruby on Rails application. From beginning I've installed all the environments using 'root' user, after installing tools I created other user - 'deploy' for Capistrano deployments. Now, when I connect to remote server with 'deploy' user account, for some reason it is showing '$ ruby -v' - 1.9.3, but I have 2.3.0 installed. when I run '$ rvm list' - it shows correct version of the ruby installed and current, same as default set to 2.3.0. When I run '$ bash --login', than '$ ruby -v' and '$ rvm list' are both showing the right version of the Ruby, so there is another issue. I think it's because I installed ruby and RVM with 'root' user, but now trying to make deployment with 'deploy' user.

Also, during deployment of the ruby application, it shows error that RAKE gem is not installed. I know for sure that RAKE and other Gems are installed.

When logged in with deploy user credentials, the 'ruby -v' shows 1.9.3, so I tried to call 'rvm use 2.3.0 --default' but error is shown:

RVM is not a function, selecting rubies with 'rvm use ...' will not work.

Thanks in advance for all your help.

change a link_to with a modal

Posted: 04 Apr 2016 08:26 AM PDT

I'm working on a project where people can be hire on a job for an event. Actually they can only "postulate" but I wan't to add the option that they can add a price with their application.

So here is my ancient code [working] :

<% if @current_user != @project.user %>      <% if project_job.users.find { |user| user == current_user } %>       <%= link_to "Retirer ma candidature", project_project_job_postulant_path(@project, project_job, project_job.postulants.find_by_user_id(current_user.id)), method: :delete, class:"btn btn-primary btn-prostate" %>      <% else %>       <%= link_to "Postuler", project_project_job_postulants_path(@project, project_job), method: :post, class:"btn btn-primary btn-prostate" %>      <% end %>    <% end %>  

And I want to do something like this :

<% if @current_user != @project.user %>    <% if project_job.users.find { |user| user == current_user } %>      <%= link_to "Retirer ma candidature", project_project_job_postulant_path(@project, project_job, project_job.postulants.find_by_user_id(current_user.id)), method: :delete, class:"btn btn-primary btn-prostate" %>    <% else %>      <div class="modal-content">        <%= simple_form_for [@project, @project_job] do |f| %>          <%= f.input :budget, required: true, autofocus: true, placeholder: "Budget moyen par personne. En Euros - €"%>          <%= f.button :submit, value: "Add", class: "btn btn-primary" %>        <% end %>      </div>    <% end %>  <% end %>  

But I have an error with autorisation maybe you could help me switching this link_to with a simple_form_for.

Thank you in advance.

EDIT : Message error You are not authorize to perform this action + Terminal

    Started POST "/projects/1/project_jobs" for ::1 at 2016-04-04 16:39:41 +0200      Processing by ProjectJobsController#create as HTML        Parameters: {"utf8"=>"✓", "authenticity_token"=>"Rs6pNdhJyuqfTQWzX2HrBzYRB+dBR3g2ZAOEoqA45pBg+zEHep79ZRTiFvz3HPZkysqUa1vqHcLDZ6neFQiPvQ==", "project_job"=>{"budget"=>"100"}, "commit"=>"Add", "project_id"=>"1"}        User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 11]]        Project Load (2.1ms)  SELECT  "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT 1  [["id", 1]]        User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]      Redirected to http://localhost:3000/      Completed 302 Found in 10ms (ActiveRecord: 2.7ms)  

ROUTES :

    Rails.application.routes.draw do        get 'project_jobs/Postulants'        root to: 'pages#home'        get '/about', to: 'pages#about'        get '/manager', to: 'pages#manager'          devise_for :users, controllers: { registrations: 'users/registrations', omniauth_callbacks: 'users/omniauth_callbacks' }        # , controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }        resources :users, only: [ :edit, :update, :show, :manager ] do          resources :skills, only: [ :edit, :create, :show, :destroy ]        end          resources :projects , only: [:new, :create, :show, :edit, :destroy, :update, :index] do          resources :project_jobs , only: [:show, :create, :destroy, :index, :new ] do            resources :postulants , only: [:show, :destroy, :index, :create]          end        end          post 'projects/:project_id/postulants/:id/accepted', to: 'postulants#accepted', as: 'accepted'        post 'projects/:project_id/postulants/:id/rejected', to: 'postulants#rejected', as: 'rejected'        post 'projects/:id/publish', to: 'projects#publish', as: 'publish'          end  

MODEL PROJECT_JOB

class ProjectJob < ActiveRecord::Base    belongs_to :project    belongs_to :job      has_many :postulants, dependent: :destroy    has_many :users, through: :postulants      validates :project_id, presence: true    validates :number, :numericality => { :greater_than => 0 }    validates :job, presence: true  end  

MODEL POSTULANT

    class Postulant < ActiveRecord::Base        belongs_to :project_job        belongs_to :user          validates :user_id, presence: true, uniqueness: { scope: :project_job,          message: "You already apply to this job" }        end  

PostulantPolicy

    class PostulantPolicy < ApplicationPolicy        class Scope < Scope          def resolve            scope          end        end          def create?          true        end            def destroy?          record.user == user        end          def accepted?          true        end          def rejected?          true        end      end  

DPRP is disabled. for this merchant in sandbox paypal

Posted: 04 Apr 2016 06:39 AM PDT

I'm trying to integrate paypal payments through card into rails app.

Normal one-time payments are working well. But I keep on getting the above response when I'm trying to make recurring payments. I've tried to enable that feature in paypal developer website but it says

Note: Live credentials are disabled for direct credit card processing in your app. We are processing your information and will email you when live API credentials are enabled.

But it is saying same from past few days. I've tried contacting them through online contact us but after three days they replied saying I have to add my credit card to the account. Do I need to add credit card for testing sandbox also?

ActiveAdmin Edit inputs missing attribute

Posted: 04 Apr 2016 06:36 AM PDT

For some reason my "Edit" page for one of my model (chart.rb) is missing on of it's attributes.

Simply adding

form do |f|      f.semantic_errors      f.inputs      f.actions  end  

to the chart.rb file will miss my attribute called type.

If I add a special field for type like so

form do |f|      f.semantic_errors      f.inputs      inputs 'test' do        input :type      end      f.actions  end  

It would properly render the type input in a nice format at another section below.

Does anyone know why f.inputs might be missing one of my Model attributes?

quick EDIT: I did a quick patch fix with the following code:

form do |f|      f.semantic_errors      f.inputs do        f.input :project        f.input :name        f.input :type        f.input :y_axis        f.input :y_max        f.input :y_min        f.input :x_axis        f.input :x_max        f.input :x_min       end      f.actions    end  

Which rendered the form just fine. But when trying to save it, I got the following error in Rails:

The single-table inheritance mechanism failed to locate the subclass: 'graph'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Chart.inheritance_column to use another column for that information.

Looks like the column name type is reserved? Is this an ActiveAdmin reservation? Hm.....

not getting first form in each loop

Posted: 04 Apr 2016 07:47 AM PDT

I have this type of each loop with form

<% @catagories.each do |cat| %>      <label>          Name:          <%= cat.name %>      </label>      <label>        Public        <%= form_for cat, :html => {:class => 'visible_in_activity_record'} do |f| %>          <%= f.check_box :visible_in_activity_record ,:'data-role'=>"none"%>        <% end %>      </label>  <% end %>  

When i show this results in browser.

First element of loop is without form and after that all element have form.

After that I tried to add code and check form from inspect element in browser but in browser that is getting same issue that i can not see form in first element of loop.

if anyone faced this type of issue then please help me to solve this.

Thank you.

Using UPSERT PostgreSQL from Rails 4.2

Posted: 04 Apr 2016 06:20 AM PDT

How do I use "UPSERT" or "INSERT INTO likes (user_id,person_id) VALUES (32,64) ON CONFLICT (user_id,person_id) DO NOTHING" in PostgreSQL 9.5 on Rails 4.2?

Using bootstrap glyphicon in rails simple form attachment

Posted: 04 Apr 2016 06:38 AM PDT

Hi all I use simple form. I have a model which contains attachment. Everything works fine except for I get a browse button in browser as shown in below image. Instead of Browse button I want bootstrap attachment glyphicon. How can I achieve this?. My code is below this image:

enter image description here

<%= simple_form_for Status.new do |f| %>    <%= f.input :status, as: :text, required: true, autofocus: true %>    <%= f.input :statachment, as: :file, label: 'Attach here' %>    <%= f.submit "Post", class: 'btn btn-primary' %>  <% end %>  

Rails use will_paginate with combined query results

Posted: 04 Apr 2016 06:34 AM PDT

In my application I have a customers model that has many payments and invoices.

# customer.rb  class Customer < ActiveRecord::Base    has_many :payments    has_many :invoices  end    # payment.rb  class Payment < ActiveRecord::Base    belongs_to :customer  end    # invoice.rb  class Invoice < ActiveRecord::Base    belongs_to :customer  end  

In the customers show template I am combining all Invoices and Payments and storing them in the @transactions instance variable.

class CustomersController < ApplicationController    def show      @customer = Customer.find(params[:id])      payments = Payment.where(customer: @customer)      invoices = Invoice.where(customer: @customer)      @transactions = payments + invoices    end  

I want to paginate @transactions using will_paginate. Doing this doesn't work:

@transactions.paginate(page: params[:page])  

What is the best way to accomplish this?

HTML, AJAX & ruby on rails message button

Posted: 04 Apr 2016 06:14 AM PDT

i would like to know how to structure the code to perform the following action,

one of the page has only one 'submit' button, when User A pressed it, a message will be generated as 'User A pressed this button!". When User B pressed the button, a message generated as 'User B pressed this button!" the messages will appear like micropost in twitter, stacking each other, and all users can view this message.

didn't manage to find guide for this simple coding anywhere, just want to know how to construct the 'submit' button to automatic send the string message based on different users.

thanks.

Clockwork gem is trying to access development db in production

Posted: 04 Apr 2016 06:36 AM PDT

I am trying to start the clockwork with following command sudo bundle exec clockwork config/clock.rb in production. But it throws the following error ActiveRecord::AdapterNotSpecified: 'development' database is not configured. Available: ["production"]. It works correctly in local. We have Puma server and JRuby setup in server.

RVM: how to get path to capistrano-installed gems

Posted: 04 Apr 2016 06:10 AM PDT

Please help before I go mad!

I've followed these instructions to create wrappers for god and unicorn on my server: RVM: how to get path to installed gems for init scripts

However, it turns out those gems don't exist under ~/.rvm.

Capistrano is installing the gems in .../shared/bundle/ruby/2.3.0

I'm not sure exactly how to resolve this... should I be creating wrappers that point to the gems created by Capistrano? Or should I be telling Capistrano to install gems in ~/.rvm ?

SPA with rails-api and Angular JS

Posted: 04 Apr 2016 06:55 AM PDT

recently I'm trying to use rails-api, I have a small project to develop and after seeing small demo of rails-api I thought it will be nice to use it as my server side. I found this tutorial:http://www.angularonrails.com/ruby-on-rails-angularjs-single-page-application/ but in this tutorial there are two separate servers and It's seems to me not like the right way to do this.

couldn't find any good tutorial that explains how to use rails-api to serve the REST and tell the server also wo serve some html/css/js - so my angular SPA will run next to the services.

I didn't try to use RubyOnRails since I have no use in the Views but maby Im wrong?

so my question is: how can I create Single Page Application with rails-api (or ruby on rails)?

with one server...

Proxy URL stream to response

Posted: 04 Apr 2016 06:06 AM PDT

I need to proxy the url content to client. The url requires auth which is not available on client. Here is the Groovy code for the same (Implemented in Grails framework) -

URL url = new URL('url')  URLConnection connection = url.openConnection();  connection.setRequestProperty("Authorization Bearer xxxxxxxx");  connection.connect()    response.setHeader "Content-Type", connection.getHeaderField("Content-Type")  response.setHeader "Content-disposition", "attachment; filename=file.ext"  response.outputStream << connection.inputStream  response.outputStream.flush()  

What will be the equivalent ruby code for the same in rails framework?

Best way to handle reserved names in a Rails App

Posted: 04 Apr 2016 06:32 AM PDT

I am working on the model of a Rails app and half of the names I need to use are reserved (and they are also the ones that make more sense within the application. I don't want to find another name). What's the best way to handle this?

I am thinking of using a prefix for all the models (for the ones with reserved words and not) My ideas for "Process":

MyProcess

TheProcess

So whatever prefix I choose, I will use it for every model:

MyUser

TheUser

Thanks!

Rails 4.0.3 - has_many through undefined method 'name' for nil:NilClass - only on production

Posted: 04 Apr 2016 07:39 AM PDT

I have a branch model

class Branch < ActiveRecord::Base      validates :name, presence: true        has_many :company_branches      has_many :companies, -> { uniq }, :through => :company_branches  end  

and a company model

class Company < ActiveRecord::Base      has_many :company_branches      has_many :branches, -> { uniq }, :through => :company_branches  end  

The company can have many branches through company_branches

class CompanyBranch < ActiveRecord::Base      belongs_to :branch, touch: true      belongs_to :company, touch: true  end  

On my local machine everything works fine but when I try to save the form on my production Server I get: NoMethodError (undefined methodname' for nil:NilClass)`

The call in my controller is @company.update_attributes(company_params) - The controller receives the branch_ids as array, like branch_ids => [1, 2, 3]

Interesting part of the controller(It fails at @company.update_attributes(company_params)):

class Admin::CompaniesController < Admin::AdminController      respond_to :html, :json      load_and_authorize_resource          def update          @company = Company.find(params[:id])          @company.update_attributes(company_params)          ....      end          private      def company_params        params.require(:company).permit(:id, branch_ids: [])      end  end  

To clarify: I tried many things and currently only have one branch on my production server. Even with that one single branch I get the error when I try to save it.

Edit: I posted the full stacktrace here: http://pastebin.com/tw6hjkyF

how to export the multiple data in csv forat which is strong in differnt db

Posted: 04 Apr 2016 07:48 AM PDT

I have 4 different modules in each modules different data's but all the modules actions i have written in one controller, now i want to export the data 4 different else in one sheet only .... tell me how export in CSV format.

Employee is the main controller in that only i have written all other actions.. personal_info , employee_qualification, Employee_proof, employee_skill, relatives these are the other modules now i need to be export the data in csv format

Best practices for integrating AuthenticityTokens in remote API's via React.js?

Posted: 04 Apr 2016 05:42 AM PDT

I'm using React.js via TouchStoneJS ( a simple mobile Cordova framework ) to access a remote API ( that I own ).

The form is relatively simple :

render () {    return (      <Container fill>        <Container fill scrollable ref="scrollContainer" className="login">            <UI.Group>            <UI.GroupBody>              <UI.LabelInput type="login" label="login" placeholder="your@email.com" />              <UI.LabelInput type="password" label="password"  placeholder="" />                          </UI.GroupBody>          </UI.Group>                <UI.Button type="primary" onTap={this.access_login}>            Sign In          </UI.Button>              <center>            <Link to="tabs:list-simple" transition="show-from-right">Forgot your password?</Link>          </center>        </Container>      </Container>    );  }  

Which I capture here, when they tap the Sign In button :

access_login () {    // var data = ..    $.ajax({      url: "https://my.app.dev/users/sign_in",      type: "POST",      data: data,      success: function(data) {      }.bind(this),      error: function: function(xl, x) {      }.bind(this)    });   },  

My issue is that I'm not sure how to capture an authenticity token from my existing site. How can I still authenticate my requests without them being apart of the environment?

How to define a nested has_one association?

Posted: 04 Apr 2016 07:46 AM PDT

Suppose we have this contrived model structure

class Apple < ActiveRecord::Base    belongs_to :fruit    has_one :tree, through: :fruit    has_one :organism, through: :tree  end    class Fruit < ActiveRecord::Base    belongs_to :tree    has_many :apples        end    class Tree < ActiveRecord::Base    belongs_to :organism    has_many :fruits  end    class Organism < ActiveRecord::Base    has_many :trees  end  

To avoid having to call @apple.fruit.tree.organism, I have definded the two has_one-through directives in Apple, and expect @apple.organism to work, but it does not. @apple.tree.organism does work.

Am I doing something wrong? Should I just define a getter method for :organism on Apple instances and be done with it?

Sorting by values in a loop

Posted: 04 Apr 2016 05:39 AM PDT

I'm trying to store FIFA Games, and set a scoreboard with a ranking system.

I shouldn't use logic in the view, but if I calculate them in the controller, it renders an error that the method user is not specified. When I put it in the loop, however, it recognizes it because the user is the looped item.

The app can already save games and calculate the winner. The app adds winner_id and loser_id to each game. Later in the scoreboard, I count how many current user_id's from the loop match all games' winner_id's and loser_id's. This keeps the database clean. I don't want to keep the wins and losses in the db because when a game is deleted, it shouldn't count as a win or loss anymore.

Controller:

class ScoreboardController < ApplicationController      def index          @users = User.all      end  end  

VIEW:

<div class="panel panel-default" style="margin-left: 10px; margin-right:10px">    <!-- Default panel contents -->    <div class="panel-heading">Scoreboard</div>      <!-- Table -->            <table class="table">               <thead>                   <th>#</th>                   <th>Username</th>                   <th>Ratio</th>                   <th>Wins</th>                   <th>Losses</th>                </thead>                  <% @users.each do |user|%>                    <tbody>                   <td>                 1                   </td>                  <td>                    <%= user.username %>                </td>                      <% if (Game.where(:winner_id => user.id).count) == 0 %>                      <td>Unvalid</td>                    <% elsif (Game.where(:loser_id => user.id).count) == 0 %>                         <td>Unvalid</td>                         <% else %>                            <% @ratio =  (number_with_precision((((Game.where(:winner_id => user.id).count).to_f) / (Game.where(:loser_id => user.id).count).to_f), precision: 2))  %>                         <td><%= @ratio %></td>                           <% end %>                    <td>                   <%= Game.where(:winner_id => user.id).count %>                </td>                 <td>                     <%= Game.where(:loser_id => user.id).count %>                </td>                           <% end %>                </tbody>            </table>            </div>  

I'd like to put this list in the right order. The list should be ordered by ratio. => the @ratio from the view. Can I do this directly?

In the first td, the current position is shown. It shows 1 for every user. How can I make this 1, 2, 3, ...?

has_many through belongs_to with a has_many

Posted: 04 Apr 2016 07:19 AM PDT

This is what I want to achive:

class a    belongs_to :b    has_many :placeholder, trough: :b, class_name: 'a'  end    class b    has_many :a  end  

Is this possible without a jointable? Tried different combinations of class_name and source options to the has_many through but no success so far. Either I get stuck on a source not found even-though it was provided or I ends up in a mysterious No block given error. Even tried to delegate from :b to :a.

Maybe someone can enlighten me if its even possible, when yes: how?

best regards

Rails: How to set the grandparent value (association) in ActiveRecord

Posted: 04 Apr 2016 05:33 AM PDT

How can I retrieve the data in the grandparent association.

Give the following models:

class Schedule < ActiveRecord::Base    belongs_to :user    has_many :rooms    accepts_nested_attributes_for :rooms, allow_destroy: true    ...    class Room < ActiveRecord::Base    belongs_to :schedule    has_many :events    accepts_nested_attributes_for :events, allow_destroy: true    ...    class Event < ActiveRecord::Base    belongs_to :room    ...  

I'd like to get schedule.departure_date in event.rb for using callback before_save.

event.rb

class Event < ActiveRecord::Base    belongs_to :room    before_save :assign_date      private        def assign_date        self.from = DateTime.new(schedule.departure_date.year, schedule.departure_date.month, schedule.departure_date.day, from.hour, from.min)      end  

schema.rb

create_table "schedules", force: :cascade do |t|    t.date     "departure_date"    ...    create_table "rooms", force: :cascade do |t|    t.integer  "schedule_id"    ...    create_table "events", force: :cascade do |t|    t.time     "from"    t.integer  "room_id"    ...  

When I try to execute this code, the following error appeared.

development.log

NameError (undefined local variable or method `schedule' for #<Event:0x000000058bdd28>):    app/models/event.rb:15:in `assign_date'    app/controllers/schedules_controller.rb:51:in `update'  

schedules_controller.erb

  def update      @schedule.room.maximum(:day)      if @schedule.update(schedule_params)        flash[:success] = "Schedule updated!"        redirect_to root_url      else        render 'edit'      end    end    ...      private        def schedule_params        params.require(:schedule).permit(:title, :departure_date, rooms_attributes: [:id, :_destroy, :room, :day, events_attributes: [:id, :_destroy, :from, :to, :title, :detail]])      end  

I use simple_nested_form_for and simple_fields_for in my view.

It would be appreciated if you could give me how to get schedule.departure_date in the event.rb.

No comments:

Post a Comment