Monday, December 5, 2016

Rails 4.2.7.1 No route matches [POST] for update | Fixed issues

Rails 4.2.7.1 No route matches [POST] for update | Fixed issues


Rails 4.2.7.1 No route matches [POST] for update

Posted: 05 Dec 2016 08:07 AM PST

Having in routes.rb

       resources :subjectheadings do           get "delete"         end  

it will generate the following routes

       subjectheading_delete GET    /subjectheadings/:subjectheading_id/delete(.:format) subjectheadings#delete               subjectheadings POST   /subjectheadings(.:format)                           subjectheadings#create            new_subjectheading GET    /subjectheadings/new(.:format)                       subjectheadings#new           edit_subjectheading GET    /subjectheadings/:id/edit(.:format)                  subjectheadings#edit                subjectheading PATCH  /subjectheadings/:id(.:format)                       subjectheadings#update                               PUT    /subjectheadings/:id(.:format)                       subjectheadings#update                               DELETE /subjectheadings/:id(.:format)                       subjectheadings#destroy  

Then in the in the view

       <%= form_for(@subjectheading, :remote => true, :url => (@subjectheading.new_record? ? subjectheadings_path : subjectheading_path(@subjectheading))) do |f| %>  

will generate the HTML code

       <form class="edit_subjectheading" id="edit_subjectheading_30" action="/subjectheadings/30" accept-charset="UTF-8" data-remote="true" method="post">                    <input type="hidden" name="_method" value="patch">                    ...  

in the form @subjectheading.persisted? is true, but during update Rails attempts to use POST instead of PATCH

       ActionController::RoutingError (No route matches [POST] "/subjectheadings/30")  

Any clue what's wrong here?

Rails 4 + AWS: Direct Upload Image CORS

Posted: 05 Dec 2016 07:56 AM PST

I am using AWS S3 to host images for my rails 4 app and am having difficulty posting despite following this tutorial for Heroku. Initially, I was receiving a preflight error until I changed the form url to https://[bucket_region].amazonaws.com/[bucket_name].

Now when I look at the network tab in the developer tools I see:

Request URL:https://[bucket_region].amazonaws.com/[bucket_name]  Request Method:OPTIONS  Status Code:200 OK  Remote Address:52.92.76.21:443  

...but then I see a second request:

Request URL:https://[bucket_region].amazonaws.com/[bucket_name]  Request Method:POST  Status Code:400 Bad Request  Remote Address:52.92.76.21:443  

This is my CORS configuration:

<?xml version="1.0" encoding="UTF-8"?>  <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">      <CORSRule>          <AllowedOrigin>http://localhost:3000</AllowedOrigin>          <AllowedMethod>GET</AllowedMethod>          <AllowedMethod>POST</AllowedMethod>          <AllowedMethod>PUT</AllowedMethod>          <AllowedHeader>*</AllowedHeader>      </CORSRule>  </CORSConfiguration>  

...am I missing something, or am I supposed to use a different URL for the preflight and POST? By the way, I am new to CORS.

rails validates with inclusion and one value

Posted: 05 Dec 2016 07:55 AM PST

I have this in my Foo class :

MIN = 2  MAX = 42    validates :max_users,              presence: true,              inclusion: { in: MIN..MAX }  

I need to allow "0" value AND the MIN..MAX interval, how can I add zero as possible value?

Labels of checkboxes of Rails form association

Posted: 05 Dec 2016 07:49 AM PST

In my simple form I have an association to select a list of groups.

<%= f.association :groups, as: :check_boxes, :include_hidden => false, label: 'Grupos' %>  

This creates me a list of checkboxes, each with the label from the name of he group.

I also have a relation that a group belongs to a company. And I would like to add the company name to the label of the checkboxes.

So right now each checkbox has a label:

Group Name  

And I want it to be

Group Name (Company Name)  

So basically I am looking for a way to customize the label of the checkboxes created with f.association.

Rails - has_many count on validate

Posted: 05 Dec 2016 07:47 AM PST

I'm doin' some validation on a parent model that save nested attributes for a child model. My parent has_many childs and my validation checks if the count of those childs is greater than 0. It works fine for editing, since the childs are already created and saved on db, but for new records it fails, since the count always returns 0. How can I fix that?

my parent model code looks like:

class ArrendamentoContrato < ApplicationRecord          has_many :arrendamento_contrato_unidades, dependent: :destroy      validate :check_total_percentual_credito      def check_total_percentual_credito      if arrendamento_contrato_unidades.count > 0 && arrendamento_contrato_unidades.sum(&:percentual_credito).to_f != 100.0        self.errors.add :percentual_credito, I18n.t("errors.messages.percentual_credito")      end    end  end  

Turbolinks 5 working on feature tests with capybara

Posted: 05 Dec 2016 07:31 AM PST

How can you config capybara to work with Turbolinks 5? I already configured poltergeist, and js: true on my tests

RSpec.feature "Home", type: :feature, js: true do    describe "on home" do      given!(:user) { create :user }        background{ visit root_path }        scenario "can select user" do        first('.header h2', user.first_name).click        sleep 1        expect(page).to have_content user.email      end    end  end  

The only why I was able to make it work is using the sleep 1

Comparing date in Rails

Posted: 05 Dec 2016 07:45 AM PST

In my Rails app, I get some date strings like '2016-6', '2016-10' and I want to find the latest one, how to do it?

Passing variable to an rspec test

Posted: 05 Dec 2016 07:22 AM PST

I am fairly new to rspec test and I have an issue trying to test the location of a user. This a test to mock the behaviour of a country_code to block spam from specific zones.

Here is the code of my service :

class GeocodeUserAuthorizer    def initialize(user_country_code:)      @user_country_code = user_country_code    end      def authorize!      user_continent = ISO3166::Country.new(user_country_code).continent        if user_continent == 'Africa'        return true      else        return false      end    end  end  

Here is the code of my spec file:

require 'spec_helper'    describe GeocodeUserAuthorizer do    context 'with a user connecting from an authorized country' do      it { expect(GeocodeUserAuthorizer.new.authorize!(user_country_code: { "CA" })).to eql(true) }    end  end  

And here is the failure code:

Failures:

1) GeocodeUserAuthorizer with a user connecting from an authorized country Failure/Error: it { expect(GeocodeUserAuthorizer.new.authorize!(user_country_code: { "CA" })).to eql(true) } ArgumentError: missing keyword: user_country_code # ./app/services/geocode_user_authorizer.rb:2:in initialize' # ./spec/services/geocode_user_authorizer_spec.rb:16:innew' # ./spec/services/geocode_user_authorizer_spec.rb:16:in block (3 levels) in <top (required)>' # ./spec/spec_helper.rb:56:inblock (3 levels) in ' # ./spec/spec_helper.rb:56:in `block (2 levels) in '

Can anybody help?

Rails Model: How to do the relation

Posted: 05 Dec 2016 07:43 AM PST

I would like to do an app, but I am stuck on how to design the model. I have these models so far: User, Post, Tag, Like, Comment. I created for each a model, controller, view and migration file. So far so good, BUT now my question is should I just do the relations between them or create these models too: PostTag, PostLike, PostComment. You know, they would just have the relation between those, so when somebody deletes a tag in a post, he actually just deletes the relation and not the tag itself because the tag is maybe used in another post.

undefined method `image' if joins tables

Posted: 05 Dec 2016 07:43 AM PST

class Photo < ApplicationRecord   has_many :user_comments   has_many :users, through: :user_comments   has_attached_file :image   validates_attachment_content_type :image, content_type: /\Aimage/.*\z/  end    class User < ApplicationRecord   has_many :user_comments   has_many :photos, through: :user_comments  end    class UserComment < ApplicationRecord   belongs_to :photo   belongs_to :user  end  

execute [union = UserComment.joins(:user,:photo).where('photos.id = ?',1).first]- OK

execute [union.image] - ERROR NoMethodError: undefined method `image' for #UserComment:0x007fe8845fbf58

how fix ?

Pass current_admin_user.id into permit_params

Posted: 05 Dec 2016 07:14 AM PST

In my application I have 2 models: AdminUser, which has_many :announcements, and Announcement, which belongs_to :admin_user. The Announcement table has admin_user_id column in a database.

In app/admin/announcement.rb I have:

ActiveAdmin.register Announcement do     permit_params :title, :body, :admin_user_id      controller do      def new        @announcement = Announcement.new        @announcement.admin_user_id = current_admin_user.id      end    end      form do |f|      f.inputs do        f.input :title        f.input :body, as: :ckeditor      end      f.actions    end    end  

Why my controller doesn't work? When I create an announcement through activeadmin, the column admin_user_id is empty. How can I solve this issue?

How to filter in Rails the records of table using last part of a string IN an Array of values

Posted: 05 Dec 2016 07:57 AM PST

Here is what I have build in the model class

class Organization < ApplicationRecord  ...    scope :filter_by_domestic, ->(host_name_designation) do      joins("LEFT JOIN events ON events.organization_id = organizations.id").        where(events: { host_name: host_name_designation })    end    end  

I am getting correct results when I am using something like this:

@organizations = Organization.filter_by_domestic ['www.abc.com', 'www.xyz.com']  

But I would like to improve the query and get the results only on the last part of the host_name, something like all records for which host_name ends with the substring .com. I need to apply split('.')last for this where(events: { host_name: host_name_designation }) and I don't know the correct syntax for this. What is the correct statement here, in my case?

I want to be able to write something like:

  scope :filter_by_domestic, ->(host_name_designation) do      joins("LEFT JOIN events ON events.organization_id = organizations.id").        where(events: { '.' + host_name:.split('.').last host_name_designation })    end   

I need where to return something like this:

 '.' + Event.first.host_name.split('.').last    Event Load (0.4ms)  SELECT  "events".* FROM "events" ORDER BY "events"."id" ASC LIMIT $1  [["LIMIT", 1]]  => ".com"  

Practically I need only the last part of the host_name to be used in the where clause. I know how to build my own where clause to achieve this, but I am looking to have the query generated instead of developed.

Any clue?

Rails: extending alias_method_chain

Posted: 05 Dec 2016 07:49 AM PST

There is a Rails 4.2.6 application that has a core plugin extending ActiveRecord reload method via alias_method_chain.
I need to write another plugin extending the same base functionality and keeping what was added by the core plugin.
As far as I get it, I can call alias_method_chain only once but I wish to get something like this:

class Klass    def foo  end    core_plugin:    base.send :alias_method_chain, :foo, :bar    my_plugin:    base.send :alias_method_chain, :foo, :baz  

Where a call to Klass.foo results in calls to :baz, :bar and :foo

So what are my options assuming I cannot edit core_plugin?

Manually adding data to a namespaced model in rails

Posted: 05 Dec 2016 06:25 AM PST

I'm trying to manually add data to a table in rails using the rails console, but I keep getting a undefined local variable or method error.

The model is namespaced under ratings:

models/ratings/value_for_money_score.rb

class Ratings::ValueForMoneyScore < ApplicationRecord  end  

To try and manually add a record to the database, I run the following in the console:

$ RatingsValueForMoneyScore.create(score: '1', description:"Terrible, definitely not worth what was paid!")  

And I get this error: NameError: uninitialized constant RatingsValueForMoneyScore

I have tried a few different versions such as RatingsValueForMoneyScores.create, Ratings_ValueForMoneyScores.create, ratings_value_for_money_scores.create but keep getting the same error. What am I doing wrong?

ActiveAdmin custom select filter dropdown names

Posted: 05 Dec 2016 06:01 AM PST

For a user model I have a filter to check the booking status of a user which is represented by an integer value (0, 1, or 2).

The filter on the User ActiveAdmin index page is achieved with the following code:

  filter :booking_status, as: :select  

However this results in the dropdown options being either 0, 1, or 2.

I would prefer if I could name them myself to something like "Incomplete", "Pending", and "Confirmed" when the admin user is selecting them from the dropdown.

enter image description here

Is there any way of doing this without changing how the booking_status is represented in the model?

Rails routing spec with mounted Sinatra application

Posted: 05 Dec 2016 05:09 AM PST

I'm mounting a Sinatra-based gem into my application and would like to add a routing spec that verifies that the Sinatra app is indeed mounted at the correct path.

The main application should not contain any tests that are specific to the functionality of the gem because those are of course tested there.

Looking at the RSpec routing matchers and the Rails routing assertions, it seems they're only capable of dealing with controllers.

For now I have added a spec that just tests a POST request with be_routable but that's not really usable for all the routes because there's always danger of accidentally using some fallback route of the main application.

How do I effectively preload conditional associations in Rails?

Posted: 05 Dec 2016 07:16 AM PST

I have the following two models:

class Company < ActiveRecord::Base    has_many :employees # A company can have 1000's of employees.  end    class Employee < ActiveRecord::Base    belongs_to :company  end  

One of my use cases looks like this

In the controller:

def my_action    @companies = Company.where(country: 'GB').preload(:employees)    @title = params[:title] # E.g. 'CTO'  end  

In the view:

- @companies.each do |c|    = c.employees.where(title: @title).first.last_name   

The problem with the above is that it will create an N+1 in the view

Now I could change the view to:

# In the view  - @companies.each do |c|    = c.employees.select{|e| e.title == @title}.first.last_name   

This will solve the N+1 but it will still load out potentially 1000's of employee records even though I don't need them (I only need the ones with the right title).

I could solve that by:

class Company < ActiveRecord::Base    has_many :employees    has_many :ctos, ->{ where(title: 'CTO') }  end    # In the controller  def my_action    @companies = Company.where(country: 'GB').preload(:ctos)  end    # In the view  - @companies.each do |c|    = c.ctos.first.last_name   

The problem with this however is that it would require me to add associations for every single possible type on Company.

So the question is, how can I solve this?

Rails Simple Form - Add an error not related to attribute

Posted: 05 Dec 2016 05:24 AM PST

I wanna do a validation that sums the values of nested fields so I make sure it's 100%. So, in my parent model, I would do the validation, and do a self.errors.add and add the error if the validation fails. The problem is, the errors.add as long as I know expects some attribute as argument, but it's not related to any attribute on my parent model, so I would like to display that message on the top of the form, for example. Any ideas of how I can do that? thank you!

UPDATE:

This is my parent model, where I wanna validate. The form has nested fields for :arrendamento_contrato_unidades.

    class ArrendamentoContrato < ApplicationRecord          has_many :arrendamento_contrato_unidades, dependent: :destroy          validate :check_total_percentual_credito        def check_total_percentual_credito      if arrendamento_contrato_unidades.sum(&:percentual_credito).to_f != 100.0        self.errors.add :base, "Tem que ser 100%"      end    end          end  

My create method, which it's the one I'm testing:

  def create          @arrendamento_contrato = ArrendamentoContrato.new(arrendamento_contrato_params)        respond_to do |format|        if @arrendamento_contrato.save            format.html {             flash[:notice] = flash_notice            redirect_to action: "index"          }          format.json { render json: {status: 1, redirect: arrendamento_contratos_url} }        else          format.html { render :new }          format.json { render json: {status: 0, errors: @arrendamento_contrato.errors, status: :unprocessable_entity} }        end      end    end  

--- Also, I debugged my object.errors.full_messages on the form, and the error is there. It's only not being displayed!

I guess that add errors to the base it's what I'm looking for. But now, it's not showing my message, but only that I have validation errors. My form code:

= simple_form_for(@arrendamento_contrato, validate: true, html: { id:"dropzoneForm", class: "dropzone dz-clickable"}) do |f|    = f.error_notification      .form-inputs        .row          .col-md-6            = f.input :numero          .col-md-6            = f.association :usina, input_html: {class: "chosen-select"}                     .hr-line-dashed        .row          .col-md-6            = f.association :esco_contrato, input_html: {class: "chosen-select"}          .col-md-6            = f.association :om_contrato, input_html: {class: "chosen-select"}          .hr-line-dashed        .row          .col-md-4          = f.input :data_inicio, as: :string, input_html: {"data-mask" => "date"}           .col-md-4          = f.input :data_fim, as: :string, input_html: {"data-mask" => "date"}           .col-md-4          = f.input :valor_mensal, as: :string, input_html: {"data-mask" => "decimal"}          .hr-line-dashed                #arrendamento_contratos_unidades        - if !@arrendamento_contrato.arrendamento_contrato_unidades || @arrendamento_contrato.arrendamento_contrato_unidades.empty?          h3 = I18n.t('activerecord.models.unidade_consumidora.other')          i            'Aguardando ESCO...        - else          .row            .col-md-6              label class='control-label'                = I18n.t('activerecord.models.unidade_consumidora.other')            .col-md-6              label class='control-label'                = I18n.t('activerecord.attributes.arrendamento_contrato_unidade.percentual_credito')          .hr-line-dashed          .blockquote            = f.simple_fields_for :arrendamento_contrato_unidades do |f|              = render 'arrendamento_contrato_unidade_fields', f: f        .hr-line-dashed  

Rails 5, jQuery, add event to dynamically created items

Posted: 05 Dec 2016 05:01 AM PST

I have my solution working, but I believe there would be a better, more elegant way. Any ideas are very welcome.

The thing is that navbar dropdown menu items has icons left to it. I placed icon and item name in separate spans so I could style them separately. I also wrapped those with a div, since I need to change background color of both - icon and list item name if hovered.

Navbar renders links in dropdown menu:

      <ul class="dropdown-menu">          <% @categories.each do |cat| %>            <li>              <%= link_to cat do %>              <div class="main-cont"><span id="icon-cont"><i class="glyphicon glyphicon glyphicon-tag"></i></span><span id="name-cont"><%= cat[:name] %></span></div>            </li>            <% end %>          <% end %>        </ul>  

jQuery to change the background:

$(document).ready(function(){    $('.main-cont').on('mouseover', function(){      $(this).find('#icon-cont').css('background-color', 'yellow');      $(this).find('#name-cont').css('background-color', 'yellow');    });    $('.main-cont').on('mouseout', function(){      $(this).find('#icon-cont').css('background-color', '');      $(this).find('#name-cont').css('background-color', '');    });  });  

So it does the job, but especially jQuery part is a bit clumsy (HTML is also far away from "wow"). Any ways to improve it? Thanks!

controller test: <302: Found> redirect to <http://www.example.com/users/sign_in>

Posted: 05 Dec 2016 06:42 AM PST

I have a problem with unit testing in ruby on rails (rails v. 5.001). I use devise and cancancan for authorization. The user needs to login in a test unit, but how can I implement this without redirecting to http://www.example.com/users/sign_in? Here is the code:

appointments_controller_test.rb

require 'test_helper'    class AppointmentsControllerTest < ActionDispatch::IntegrationTest    include Devise::Test::IntegrationHelpers      def sign_in(user)      post user_session_path \        "heiko@me.com"    => user.email,        "hhdk#s0" => user.password    end      setup do      @heikoAppointment = appointments(:appointment_heiko)      @heiko = users(:user_heiko)      sign_in(@heiko)    end      test "should get index" do      get appointments_url      assert_response :success    end      test "should get new" do      sign_in(@heiko)      get new_appointment_url      assert_response :success    end  

And here is the Error I get when I run the test:

Error:  AppointmentsControllerTest#test_should_get_new [C:/Users/Clemens/meindorfladen/Server/test/controllers/appointments_controller_test.rb:33]:  Expected response to be a <2XX: success>, but was a <302: Found> redirect to <http://www.example.com/users/sign_in>  

Rspec rails routes Error parameter missing

Posted: 05 Dec 2016 04:51 AM PST

  RSpec.describe 'Book', :type => :request do    describe 'List Books' do      let(:book) { FactoryGirl.create :book }      before(:each) do        visit root_path      end      context 'when book is created' do        let(:book) { FactoryGirl.create :book, title: 'My Book Title' }        it 'should list books' do          post books_path({book: book})                  expect(page).to have_content 'My Book Title'        end      end      context 'when no book is created' do        it 'should not list books' do          expect(page).to have_content 'No books found'        end      end    end  end  

Failure/Error: params.require(:book).permit(:title, :abstract, :author, :pages, :price, :image_file_name, :genre, :published_on)

 ActionController::ParameterMissing:     param is missing or the value is empty: book  

Rails Friendly_ID Multiple model creation with slug on same field failing

Posted: 05 Dec 2016 04:45 AM PST

I am running a Rails 5 application which has 2 models - a User and a Provider. I am using multiple table inheritance to show that each Provider "is a" User (via the active_record-acts_as gem). So, in effect, creating a Provider with the related fields would create a User at the same time.

I wanted to implement slugging for these models, so I integrated the friendly_id gem for that purpose.

Both models are slugged via a field called username. The code in question being:

class User    extend FriendlyId    friendly_id :username, use: :slugged    # ...  end  

for the User model and

class Provider    extend FriendlyId    friendly_id username, use: :slugged      def username      acting_as.username # this fetches the parent model (User)'s username field.    end    # ...  end  

for the Provider model.

When I attempt to create a Provider via a controller action (providers#create), it fails, with the error being:

TypeError at /providers  nil is not a symbol nor a string  

The stack trace identifies the problem to be at lib/friendly_id/slugged.rb:299, which is the body of the should_generate_new_friendly_id? method. This method was called by the set_slug method in the same file, slugged.rb.

I have created an issue on the GitHub page of friendly_id, where you can find the request parameters and full stack trace.

Edit: added friendly_id_config for both: https://gist.github.com/mindseyeblind/9b78c588f5008a494f7157e72da1de6e

Rails ruby code inside xml

Posted: 05 Dec 2016 04:06 AM PST

I have xml and want add ruby code in it.

When have done <Date><%= params[:date] %></Date> it works ok

but when i need

<PTC Quantity=<%= params[:travellers]['ADT']%> >ADT</PTC>  

after it i have got syntax error

original xml for PTC <PTC Quantity="1">ADT</PTC>

How to add ruby code to nested xml values?

Rails convention for non-index integer fields

Posted: 05 Dec 2016 04:59 AM PST

I want to keep statistics of records (let's say books), that how many times they've displayed on a page. I've added an integer column called featured, based on that attribute, I'm fetching records which has less count of featured. This will reduce inequality and I will be happy, because I am a communist :)

def foo    @books = Book.order(:featured).take(5)    @books.each { |book| book.update_columns(featured: book.featured+1) }    render 'bar'    end  

Suddenly I've realized that attributes with ed suffix ( past (perfect) tense ) are generally used for boolean fields (e.g. book.published?, book.featured?, book.approved?), which is more intuitive. And if I keep featured as an integer attribute name, this may confuse other newcomers in future.

So, is there a more readable convention for integer fields?

Rails4: How to pass dynamic array from view to controller

Posted: 05 Dec 2016 03:34 AM PST

I have a problem creating Vote which contains value of points that user decided to give for a candidate (Borda Count Method). Values are in number_fields and I want them to be saved in Vote objects.

In my case I am only able to get value from the last number_field and I have no idea how to fix it. Other values are being overwritten so I came up with idea to create an array of points which contains values taken from many number_field_tag and pass them from view to controller.

Something about survey structure: There is a Surv (survey) which contains many Polls (questions). One Poll contains many Vote Options. There are also Votes which save votes of user.

OUTPUT from params

{"utf8"=>"✓", "poll"=>{"id"=>"11"}, "9"=>"17", "arr"=>"1212", "pnts"=>"", "10"=>"20", "11"=>"22", "commit"=>"Zagłosuj", "controller"=>"votes", "action"=>"create"}  

VIEW:

show.html.erb

<p id="notice"><%= notice %></p>  <h2>Twoja ankieta:</h2>    <h1>    <%= @surv.topic %>  </h1>  <h2>    <%= election_type %>  </h2>    <%= render 'voting_form' %>    <%= link_to 'Edit', edit_surv_path(@surv) %> |  

_voting_form.html.erb

<%= form_tag votes_path, method: :post, remote: true, id: 'voting_form' do %>    <% if @surv.votingtype == "default" %>     <%# here is unnecessary code ... %>  <% elsif @surv.votingtype == "bordy" %>  <%# BORDY %>    <% @polls.each do |poll| %>      <h2><%= poll.topic %></h2>      <h2>POLL ID: <%= poll.id %></h2>      <%= hidden_field_tag 'poll[id]', poll.id %>        <%= arr = [] %>    <%= i = 0 %>      <% poll.vote_options.each do |option| %>          <div class="form-group">            <%= content_tag(:label) do %>              <div class="select">              <%= option.title %>                <%= radio_button_tag option.poll_id, option.id %>                   <%# if selected then vote is created %>                <%= number_field_tag :point %>              <%#= arr << :point %>              <%= hidden_field_tag 'pnts', arr %>                  <%# some tries to pass params %>              </div>              <% end %>          <%= visualize_votes_for option %>          </div>        <% end %>        <p><b>Głosów razem: <%= poll.votes_summary %></b></p>    <% end %>      <% if current_user && current_user.voted_for3?(@surv) %>      <p>Twój głos został DO ANKIETY został zapisany.</p>    <% else %>      <%= submit_tag 'Zagłosuj', class: 'btn btn-lg btn-primary' %>    <% end %>    <% end %>      <% end %>  

CONTROLLER:

votes_controller.rb

class VotesController < ApplicationController  def create      @poll = Poll.find_by_id(params[:poll][:id])      @surv = Surv.find_by_id(@poll.surv_id)        puts "Surv id:"      puts @surv.id        @surv.polls.each do |p|        puts "Poll ID (poll voted)."        puts p.id          puts "Vote option ID (vote option voted)"        puts params[p.id.to_s]          @option = p.vote_options.find_by_id(params[p.id.to_s])        if p && !current_user.voted_for?(p)          #here i would like to grab params specially specified for each poll          @vote = @option.votes.create({user_id: current_user.id, points: params[:pnts]})          #@vote = @option.votes.create({user_id: current_user.id, points: params[:point]})          puts 'POINTS'          puts params.inspect        else          render js: 'alert(\'Glosowales juz w tej ankiecie!\');'          return        end          # end      end        @surv.update_attribute(:actual_votes, @surv.actual_votes+1)       if (@surv.maximum_votes > 0 && @surv.actual_votes >= @surv.maximum_votes)         respond_to do |format|           format.html { redirect_to terminate_surv_path(@surv), notice: 'Ostatni głos został oddany' }           format.js {render inline: "location.reload();" }         end      end    end    def vote_params    params.require(:vote).permit(:points)  end    end  

MODEL:

vote_option.rb

class VoteOption < ActiveRecord::Base    belongs_to :surv    accepts_nested_attributes_for :surv      belongs_to :poll    accepts_nested_attributes_for :poll      has_many :votes, dependent: :destroy    has_many :users, through: :votes      validates :title, presence: true  end  

vote.rb

class Vote < ActiveRecord::Base    belongs_to :user    belongs_to :vote_option  end    def surv_params    params.require(:surv).permit(:topic, :votingtype,      polls_attributes: [:id, :topic, :endtime, :endontime, :_destroy,      vote_options_attributes: [:id, :title, :_destroy]      ])  end  

Please let me know if you need some additional code or informations to help me fix my problem. Thank you in advance

Overriding <tr> styling for <td> using sass

Posted: 05 Dec 2016 04:19 AM PST

I'm currently working on a rails application where I want to highlight a row with a background colour, but in addition to that, within that row highlight a data cell with a different colour.

The problem I have is the styling for the td appears to be ignored. I just get the background colour for the whole row.

Inspecting the css client side it appears that the styling I apply for the td simply isn't there.

The generated html

<table id="project-table" class="table table-hover">    <thead>      <tr>        <th>Row</th>        <th>Fubar</th>      </tr>    </thead>      <tbody>      <tr class="clickable-row cheese">        <td>Row 1</td>        <td class="'wibble'">Hello World</td>      </tr>    </tbody>  </table>  

The sass

#project-table tbody tr.cheese {    background-color: yellow;      & td.wibble {      background-color: blue;    }  }  

What am I doing wrong?

ps: using bootstrap 3 but I don't think that's relevant to this issue, is it?

UPDATE [SOLVED]

Ok, it appears I was being blind and hadn't realised an extra set of double quotes were being generated for class="'wibble'" - thanks to @Dekel for quickly pointing that out, and allowing me to find the cause of the real issue.

To solve the issue of the generation of extra quotes I had to mark the output as html_safe:

<td<%= ((index == @project.active_pattern_index) ? ' class="wibble"' : '').html_safe %>>    <%= pattern.row(count).instruction %>  </td>  

Test controller failed: NoMethodError: undefined method `env' for nil:NilClass

Posted: 05 Dec 2016 06:08 AM PST

I have a problem with unit testing in ruby on rails (rails v. 5.001). The user needs to login in a test unit, but how can I implement this? Here is the code:

appointments_controller_test.rb

require 'test_helper'    class AppointmentsControllerTest < ActionDispatch::IntegrationTest    include Devise::TestHelpers    setup do      @heikoAppointment = appointments(:appointment_heiko)      @heiko = users(:heiko)      heiko = users(:heiko)      end      test "should get index" do      get appointments_url      assert_response :success    end      test "should get new" do      sign_in @heiko      get new_appointment_url      assert_response :success    end  

......

appointments_controller.rb

class AppointmentsController < ApplicationController    load_and_authorize_resource    layout 'appointment', only: [:shopper_show, :senior_show]      def index      @shopping_lists = ShoppingList.where(user_id: current_user.id)      @users = User.senior.where.not(id: current_user.id).order(:firstname)        #@appointments = Appointment.where(user_id: current_user.id)      #@invitations = Invitation.where(user_id: current_user.id)      #todo: merge @invitations.appointmen into @appointments    end      # GET /shopping_processes/1    # GET /shopping_processes/1.json    def show      @appointment = Appointment.find(params[:id])      @shopping_lists = get_both_lists      @users = get_both_users    end      # POST /shopping_processes    # POST /shopping_processes.json    def create      @appointment.status = nil      @appointment.processed = nil      @appointment.user_id = current_user.id        sl_created  = create_shopping_list?        respond_to do |format|        if @appointment.save          format.html { redirect_to @appointment, notice: t(:appointment_created) }          format.json { render :show, status: :created, location: @appointment }        else          if sl_created            ShoppingList.find(@appointment.shopping_list_id).destroy          end          format.html { render :new }          format.json { render json: @appointment.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /shopping_processes/1    # PATCH/PUT /shopping_processes/1.json    def update      respond_to do |format|        if @appointment.update(appointment_params)          format.html { redirect_to @appointment, notice: t(:appointment_updated) }          format.json { render :show, status: :ok, location: @appointment }        else          format.html { render :edit }          format.json { render json: @appointment.errors, status: :unprocessable_entity }        end      end    end      # DELETE /shopping_processes/1    # DELETE /shopping_processes/1.json    def destroy      @appointment.destroy      respond_to do |format|        format.html { redirect_to appointments_url, notice: t(:appointment_deleted) }        format.json { head :no_content }      end    end      def shopper_index    end      def ready_index      appointments_hash = {}        customers = User.where.not(current_appointment: nil).where(role: :senior)      customers.each {|user| appointments_hash[user.current_appointment.id] = user.current_appointment}        shoppers = User.where.not(current_appointment: nil).where(role: :shopper)      shoppers.each {|user| appointments_hash.delete(user.current_appointment.id)}        @appointments = []      appointments_hash.each { |appointment_id, appointment| @appointments.push(appointment)}    end      def shopper_show      @appointment = Appointment.find(params[:id])      @shopping_lists = get_both_lists        both_users = get_both_users      @users = {}      first = true      both_users.each do |user|        @users[user.id] = {color: (first ? 'blue' : 'yellow'), name: user.firstname + ' ' + user.lastname}        first = false      end    end      def senior_show      @appointment = Appointment.find(params[:id])          if @appointment.user == current_user          @shopping_list = @appointment.shopping_list        else          @shopping_list = @appointment.invitation.shopping_list        end        #D.S.:Diese zuweisung funktioniert nicht richtig. Sie wurde vor den DB änderung erstellt und muss angepasst werden      #D.S.:ShoppingItem.joins(:list_item) und ListItem.where(shopping_list_id: @shopping_list.id]) ergeben ein korrektes Resultat      #D.S.:Aber zusammengenommen ist die query leer      #@shopping_items = ShoppingItem.joins(:list_item).where(list_item: [shopping_list_id: @shopping_list.id])    end       private def get_both_lists      shopping_lists = [ @appointment.shopping_list]        if @appointment.invitation && @appointment.invitation.shopping_list        shopping_lists << @appointment.invitation.shopping_list      end        shopping_lists    end      private def get_both_users      users = [ @appointment.user]        if @appointment.invitation        users.push(@appointment.invitation.user)      end        users    end      private      # Use callbacks to share common setup or constraints between actions.      def set_appointment        @appointment = Appointment.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def appointment_params        params.require(:appointment).permit(:shopper_id, :status, :appointed, :processed, :shopping_list_id, invitation_attributes: [:user_id, :message ])      end      def create_shopping_list?      if @appointment.shopping_list_id.blank?        name = "Liste für den " + @appointment.appointed.strftime("%d.%m.%Y").to_s        invitee_id = "" + (@appointment.invitation.user_id.to_s) if @appointment.invitation        name = name + ( " mit " + User.find(invitee_id).firstname) unless invitee_id.blank?        sl = current_user.shopping_lists.create(:name => name)        @appointment.shopping_list_id = sl.id        true      else        false      end    end  end  

And here is the Error I get when I run the test:

Error:  AppointmentsControllerTest#test_should_get_new:  NoMethodError: undefined method `env' for nil:NilClass  

Does somebody know the solution? I would be very thankful

UPDATE: include Devise::TestHelpers is deprecated. Now I use include Devise::Test::IntegrationHelpers. Now my appointments_controller_test.rb looks like this:

 require 'test_helper'    class AppointmentsControllerTest < ActionDispatch::IntegrationTest     include Devise::Test::IntegrationHelpers      def sign_in(user)      post user_session_path \        "heiko@me.com"    => user.email,        "hhdk#s0" => user.password    end      setup do      @heikoAppointment = appointments(:appointment_heiko)      @heiko = users(:user_heiko)      sign_in(@heiko)    end      test "should get index" do      get appointments_url      assert_response :success    end      test "should get new" do      sign_in(@heiko)      get new_appointment_url      assert_response :success    end  

However I get another error:

AppointmentsControllerTest#test_should_get_new [C:/Users/Clemens/meindorfladen/Server/test/controllers/appointments_controller_test.rb:33]:  Expected response to be a <2XX: success>, but was a <302: Found> redirect to <http://www.example.com/users/sign_in>  

Does somebody knows why there is this redirect to http://www.example.com/users/sign_in? I thought now the user is signed in

How to group collection by columns

Posted: 05 Dec 2016 06:02 AM PST

I am trying to group my product properties by the property set that they below to, i.e. I have Size as a property set and wish to group under it Small, Medium, Large etc..

This is the code I currently have but I am getting a few errors

- Property.all.group_by(&:property_set_id).each do |property_set, properties|    h3= property_set.name  - properties.each do |property|    = property.property_set.name    .property_form.left.span-9.last      - checked = property_set.name && property_set.properties.include?(property)      label.mdl-switch.mdl-js-switch.mdl-js-ripple-effect for=property.name        = check_box_tag "prototype[property_ids][]", property.id, checked, :class => 'mdl-switch__input', :id => property.name        span.mdl-switch__label= property.name        def edit      @properties = Property.all      @property_set = PropertySet.includes(:properties).find(params[:id])    end  

Converting array of objects into array of strings

Posted: 05 Dec 2016 03:15 AM PST

I'm working on an app where I need to pass an array of strings to a backend service something like

const ids = [];   for (let i = 0; i < pIds.length; i++) {     ids.push(pIds[i].id);  }   // pIds is an array of objects [{id: 2, name: 'dd'}]      this.webClient = new Frisbee({    baseURI: `${Secrets.url_host}/api/v1`,    headers: {      Accept: 'application/json',      'Content-Type': 'application/json',    },  });    getData({ continuation = 1, q = '', ids = '' }) {   return this.webClient.get('/whatever', {    body: {      'platform_ids': ids,    },  }).then(getContent);  

}

after running this code if get an array of ids [2,3] for example

but when I pass it to the backend (ruby on rails ) it arrive like that

[{"0"=>"1", "1"=>"2"}]  

What can I do to get it as ["1", "2"]? I've tried many solutions but nothing works.

Rails, mapbox and geocoder : find object near another object

Posted: 05 Dec 2016 04:04 AM PST

I try to find an object @center near an object @school depending the location, and show the center on mapbox. I past my code here because I'm not sure of what I did :

here is the code displaying map (with 2 data : school and center) :

<div id="school-map" data-coordinates="<%= @school.coordinates.reverse %>" data-centers="<%= @center.coordinates.reverse %>"> </div>  

here is the center.rb model :

class Center    include Mongoid::Document    include Geocoder::Model::Mongoid      has_many :schools    accepts_nested_attributes_for :schools      field :title,             type: String      field :image_path,        type: String    field :Attachment_path,   type: String    field :website,           type: String      field :phone,             type: String      field :street,            type: String    field :zipcode,           type: String    field :city,              type: String    field :coordinates,       type: Array      geocoded_by :adress    #after_validation :geocode      def adress      [street, zipcode, city].compact.joint(', ')    end    end  

In school.rb model, I try this method :

   def center_near_school(school_adress_coordinates)  school_adress_coordinates = @school.coordinates.reverse  center = Center.near(school_adress_coordinates, 1, units: :km)  

end

and I try to show string like "yes" or "no" to know if my method work :

<% if @school.center_near_school %>              <p> OUI </p>            <% else %>              <p> NON </p>            <% end %>  

I create relation (has_many :schools, and has_many :centers) in both models, the markers generations are created in show.js which displaying the map.

Does someone could help me to find some solutions to create this functionality ?

Don't hesitate to ask me to edit this post with more informations (code, precisions ...)

thank !

1 comment:

  1. Rails 4.2.7.1 No Route Matches [Post] For Update >>>>> Download Now

    >>>>> Download Full

    Rails 4.2.7.1 No Route Matches [Post] For Update >>>>> Download LINK

    >>>>> Download Now

    Rails 4.2.7.1 No Route Matches [Post] For Update >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete