Tuesday, July 19, 2016

Rails get the parent from the AR relation of a has_many | Fixed issues

Rails get the parent from the AR relation of a has_many | Fixed issues


Rails get the parent from the AR relation of a has_many

Posted: 19 Jul 2016 08:14 AM PDT

I have a model Client which has_many :analytics and Analytic which belongs_to :client. I have written a method in the analytic model to update itself for a given client and basically want to call Client.find(xx).analytics.update_analytics(arg1, arg2,..)

The code in Analytic.rb looks something like this:

def self.update_analytics(arg1, arg2, ...)    client = self.client  end  

The self.client errors out undefined method and self.parent just returns Object but I cannot call self.parent.id or other attributes from the parent.

How do I get the Client instance that called the analytics.update_analytics method inside of it?

Attach document using carrierwave from console

Posted: 19 Jul 2016 08:00 AM PDT

I have a document 'example.docx' located in public folder of my app.

I want to create a subject record from the console that has that document attached using carrierwave gem like this:

Subject.create(group_id: 3, type: 1, attachment: __________)  

subject.rb:

mount_uploader :attachment, FileUploader  

Replacing gem's vendor assets in Rails 5

Posted: 19 Jul 2016 08:00 AM PDT

I'm trying out Trix (https://github.com/basecamp/trix) on my Rails 5 project using the Trix gem (https://github.com/maclover7/trix).

In Rails 5, how do you go about replacing / overriding a gem's assets in the vendor directory.

I've tried adding the following:

vendor/assets/stylesheets/trix/trix.css  vendor/assets/stylesheets/trix.css  vendor/assets/stylesheets/trix/trix.scss  vendor/assets/stylesheets/trix/trix.csss  

My application's application.scss file contains

@import "vars";  @import "trix"; # App is picking up the asset from the gem  @import "header";  @import "post"  @import "footer";  

The same goes for vendor javascripts where I've tried creating a file in vendor/assets/javascript/trix/config/toolbar.coffee

Rails remote form not submitting with JS when signature-pad present

Posted: 19 Jul 2016 07:59 AM PDT

I have a rails form with remote: true which I submit after some processing with JavaScript. I do it using jQuery:

$form.submit()  

Everything works fine until I add https://github.com/thomasjbradley/signature-pad to the form (and some hidden inputs to send canvas data to the server). With signature-pad present form submitting stops working - there are no new requests in Network tab in Chrome developer console when I use the above method to submit the form.

Calling .submit() on HTML element object instead of jQuery object $form[0].submit() submits the form in a regular way without AJAX.

Method described in this post How to reliably submit an HTML form with JavaScript? also submits the form in a regular way without AJAX.

Rails carrierwave versions

Posted: 19 Jul 2016 07:56 AM PDT

I want to do some versioning while uploading.

The thumbnail is generated, but the :ogg version is not processed. What could be causing this?

  #Erzeugt ein Thumbnail    version :thumb do      process thumbnail: [{format: 'png', quality: 10, size: 1200, strip: false, seek: 10, logger: Rails.logger}]        def full_filename for_file        png_name for_file, version_name      end    end      version :ogg do      puts "OGGGGGGGGGGGGGGGGGGGGGGG"    end  

Rails- Show errors in a partial

Posted: 19 Jul 2016 08:10 AM PDT

In my form partial, I want to have a function that would display the errors if the validations in the model are not "true". But I have an error that appears when I attempt to go into a page that renders the form partial.

The error:

syntax error, unexpected keyword_ensure, expecting end-of-input    <%= render partial: 'form', locals: {submission_link: "/candidates"} %> #this is the code highlighted  

_form.html.erb:

<div class = "box well bs-content">  <%= simple_form_for(@candidates, url: submission_link) do |c| %>    <% if @candidates.errors.any? %>  <ul>  <% @candidates.errors.full_messages.each do |message| %>    <li><%= message %></li>   <% end %>  </ul>    <% end %>      <%= c.input :first_name %>  <%= c.input :last_name %>  <%= c.input :nickname %>  <%= c.input :slogan, as: :text %>  <%= c.association :position %>  <% if c.object.image? %>      <%= image_tag c.object.image.thumb.url %>  <% end %>  <%= c.label :image %><br>  <%= c.file_field :image %>  <% if c.object.image? %>      <%= c.label :remove_image %>      <%= c.check_box :remove_image %> <br>  <% end %>        <%= c.button :submit, "Submit" %>  <%= link_to "Back", candidates_path, class: 'btn btn-info' %>  <% end %>      </div>  

routes.rb

Rails.application.routes.draw do      devise_for :voters    devise_for :admins    root 'candidates#index'      # Position    get '/positions', to: 'positions#index', as: :positions    post '/positions', to: 'positions#create', as: :position    get '/positions/new', to: 'positions#new', as: :new_position    get '/positions/edit/:id', to: 'positions#edit', as: :edit_position    patch 'positions/update/:id', to: 'positions#update', as: :update_position    get '/positions/show/:id', to: 'positions#show', as: :show_position    get '/positions/delete/:id', to: 'positions#delete', as: :delete_position        #Candidate    get '/candidates', to: 'candidates#index', as: :candidates    post '/candidates', to: 'candidates#create', as: :candidate    get '/candidates/new', to: 'candidates#new', as: :new_candidate    get '/candidates/edit/:id', to: 'candidates#edit', as: :edit_candidate    patch 'candidates/update/:id', to: 'candidates#update', as: :update_candidate    get '/candidates/show/:id', to: 'candidates#show', as: :show_candidate    get '/candidates/delete/:id', to: 'candidates#delete', as: :delete_candidate      get '/about', to: 'candidates#about', as: :about      get '/vote/:id', to: 'votes#index', as: :vote    post '/vote/submit', to: 'votes#submit', as: :vote_submit    get '/vote/ballot/:id', to: 'votes#ballot', as: :vote_ballot      #Voter    match '/voter',     to: 'voters#show',       via: 'get', as: :show_voters   end  

Rails 4: Validate file, then import if conditions met

Posted: 19 Jul 2016 07:50 AM PDT

I am importing a file using SmarterCSV and I have 1 function that validates certain aspects of the file, and then redirects you, displaying the results.

I would like this display to also include a button that says "import", which allows you to import that same file as long as you are satisfied with what is displayed.

How can I pass the file to the second function after redirect without having to select the file again?

# validate file and check display  def check_file      @success, @error = Timecard.check_timecard(params[:file])      redirect_to timecards_path, notice: [@success, @error]  end    #import into database if display is satisfactory  def bulk_upload      x = Timecard.import(params[:file])      redirect_to timecards_path, notice: "Times imported successfully."  end    #view showing display  <% if flash[:notice].is_a? String %>      <%= flash[:notice] %>  <% elsif flash[:notice].is_a? Array %>      <div class="container">          <div class="col-xs-10 col-xs-offset-1">              <table class="table table-hover table-striped table-bordered">                  <thead>                      <tr>                          <th>Name</th>                          <th>Regular</th>                          <th>Overtime</th>                          <th>Sick</th>                          <th>Vacation</th>                          <th>Holiday</th>                      </tr>                  </thead>                  <tbody>                      <% notice[0].each do |success| %>                      <tr>                          <td style="color: green"><%= success[0] %></td>                          <% success[1].each do |type| %>                          <td><%= type %></td>                          <% end %>                      </tr>                      <% end %>                      <% notice[1].each do |failure| %>                      <tr>                          <td style="color: red"><%= failure[0] %></td>                          <td><%= success[1] %></td>                      </tr>                      <% end %>                  </tbody>              </table>          </div>            <div class="container-fluid">              <div class="col-xs-12 col-md-6 col-md-offset-3 text-xs-center">                  <div class="card card-nav-tabs">                      <div class="header header-info">                          Import Timecard and Send Email                      </div>                      <div class="content">                          <!-- IMPORT GOES HERE -->                        </div>                  </div>              </div>          </div>      </div>  <% end %>  

Rails: don't refresh page after modal action/submit

Posted: 19 Jul 2016 07:47 AM PDT

I have a modal which opens on top of another screen. The base screen has a filter method that uses AJAX to filter the results on that page.

After, I filter the results on the screen, I can open the modal and perform an action on the form in the modal. However, I don't want to perform a redirect/refresh.

How do I do this while still performing the submission?

My modal link is like:

<%= link_to this_path(user_id: user.id), class:"modal-link", data: {"modal-url" => this_path(user_id: user.id)} do %><span><i class="fa fa-plus"></i><% end %>  

The modal is standard enough:

<div class="modal form-modal">      <div class="modal-container">          <div class="modal-dialog modal-dialog-wide">              <button class="close">&times;</button>              <div class="modal-content">                  <div class="modal-header">                      <h2 class="hdg-b">Edit This</h2>                  </div>                  <div class="modal-body">                      <div id="error_explanation"></div>                      <%= render 'form', form_path: action_path, form_method: :put, create: false %>                  </div>              </div>          </div>      </div>  </div>  

The AJAX is too:

MyProject.onPageLoad(function() {    var form  = $('.edit_site_scope'),    onSubmit  = function(event) {     //callback handler for form submit                  event.preventDefault();                  var form     = $(this),                  url          = form.attr("action"), //get form action:                  type         = form.attr("method"),                  data         = form.serialize();                  var location = window.location.href;                    var posting  = $.ajax({                    type: type,                    url: url,                    data: data,                    dayaType: "json",                    success:function(data, textStatus, jqXHR)                     {                       $('.modal').remove();                      window.location = location;                      $('#contact-tab-submit').show();                    },                    error: function(jqXHR, textStatus, errorThrown)                     {                      $('#error_explanation').html('');                      errors = jqXHR.responseJSON;                      $.each( errors, function( key, value ) {                        $('#error_explanation').append('<div class="alert alert-dismissable" id="alert-message"><i class="fa fa-exclamation-triangle"></i>' + value + '<div class="alert-close">Close</div></div>');                      });                      $('#contact-tab-submit').show();                    }                  });                    window.setTimeout(function() {                    $(".alert").fadeTo(500, 0).slideUp(500, function(){                        $(this).remove();                     });                  }, 5000);                    return false; // prevent default when submit button clicked    };    if (form.size() !== 0)  {        form.submit(onSubmit);    }  });  

And here is my controller action on the form submit:

def action_to_be_performed      @this_thing = ThisThing.where(id: params[:id]).first      @this_thing.update(this_things_params)      flash[:success] = "Successfully performed the action."      render json: @this_thing    rescue => error      Rails.logger.error "Exception caught updating this.\nCause: #{error}\n" + error.backtrace.join("\n")      render json: @this_thing.errors.full_messages, status: :bad_request    end  

I really struggle with modals still and I guess with AJAX. How do I perform my action, close the modal and keep the current page open?

Using Ruby on Rails, How can I put data in a new table line?

Posted: 19 Jul 2016 08:14 AM PDT

I'm a beginner in Ruby on Rails. And I'm korean. So my words are little weired... My question is this... If I have 10 data, I want to put 1~5th data in a first line and 6~10th data in a second line.

like this

I've try this codes

              <table border height=300 width=300 align=center>                  <thead>                    <tr style="font size:20;">                      <th></th>                      <th></th>                    </tr>                  </thead>                    <tbody>                    <% if current_user.samulham.nil? %>                      <tr>                        <% @samulham.each do |x| %>                           <% if x.user_id.present?%>                             <td><%= "X" %></td>                           <% else %>                             <td><%= link_to "#{x.lockernumber}", {:controller => "home", :action => "register", :cur_user => current_user.id, :cur_samulham => x.id}, method: :post %></td>                           <% end %>                        <% end %>                      </tr>                    <% end %>                  </tbody>                </table>  

Thank you for your considering. :)

Making ActiveRecord sanitization methods available in class

Posted: 19 Jul 2016 07:34 AM PDT

I am building a filter class that constructs special sql queries. It's a service class, not a model and has no underlying table.

I want to sanitize the input when embedding it into the sql, to safeguard against injection.
These methods do exactly what I want: http://api.rubyonrails.org/classes/ActiveRecord/Sanitization/ClassMethods.html

However, using include ActiveRecord::Sanitization does not work. When I call sanitize_sql_array it complains:

Undefined local variable or method `connection` Applications::ApplicationFilter:Class  

Which is seemingly some kind of dependency issue. When I inherit my filter class from AR, with Applications::ApplicationFilter < ActiveRecord::Base, then it works. But I don't want to do that.. please.. please please please

Does anyone know how to make this sanitize_sql_array method available without inheriting from the whole big lumpy activerecord rhinoserous?

How do I start my Rails Background Worker automatically in Production Environment

Posted: 19 Jul 2016 07:36 AM PDT

I figured out that I start my background worker manually on Develoment Environment.

My payments/transactions will not get successful if my background worker is not running.

What I have done

I created a Procfile and inside it I have the following such that I this below:

ApplicationName/Procfile

worker: bundle exec rake jobs:work   

Will this actually solve my problem if I deploy my application? And if not, how do I start background worker on Production?

bind with ajax:success is not working rails 4

Posted: 19 Jul 2016 08:10 AM PDT

I have a jquery function in rails app from which I am trying to make ajax call.

The problem is its not returning ajax response but its sending ajax call.

I need to bind my ajax call with that function.

Here is the js code:

$(document).ready(function () {      $("#contact_us").bind("ajax:success", function (e, data, status, xhr) {          if (data.success) {              $("#alert_success").show();              $(".CaptchaError").html(data.message);          } else {              $("#alert_failed").show();              $(".CaptchaError").html(data.message);          }      });  });  

And its Rails Code:

def check_captcha      unless verify_recaptcha        return render json: {:success => false, :message => "You cant use this captcha code"}      else        contact_us        return render json: {:success => true, :message => "Your email has been sent successfully"}      end    end  

Here is my rails form:

<%=form_tag contact_us_mail_index_path, :id => "contact_us", :format => :json, :remote => true do %>  <%end%>  

Can you embed forms and associate elements with specific form

Posted: 19 Jul 2016 07:17 AM PDT

I have a table whereby there are two columns containing checkboxes, one for approving and declining. My intention is that you can either approve or reject a row by clicking the associated checkbox and then clicking the reject or approve buttons at the bottom.

The problem is I am generating the table through iteration and the way my code is structured means that a form is being generated for every row.

        - @campaigns.each do |campaign|            %tr.medium              %td= link_to campaign.name              %td= campaign.created_at              %td= campaign.service              %td= campaign.price              %td= campaign.freq              %td= campaign.start_date              %td= campaign.revenue              %td= campaign.status              %td                %form{:name => "approve_path", :id => campaign, :method => "post", :enctype => "text/plain"}                  = check_box_tag 'campaigns[]', campaign.id, false, {id: "c#{campaign.id}", class: "approvedservices"}              %td                %form{:name => "reject_path", :id => campaign, :method => "put", :enctype => "text/plain"}                  = check_box_tag 'campaigns[]', campaign.id, false, {id: "c#{campaign.id}", class: "rejectedservices"}        %tr.medium          %td.white{:colspan => 8}          %td.white            %span.input-group-btn              %button.btn.btn-success#approvedservicesbutton{:type => "submit", :style => "width: 100%; height:34px;", "data-toggle" => "tooltip", title: "Approve"}          %td.white            %span.input-group-btn              %button.btn.btn-danger#rejectedservicesbutton{:type => "submit", :style => "width: 100%; height:34px;", "data-toggle" => "tooltip", title: "Reject"}  

As you can see the way I have it structured means for every row a new form is created and the submit buttons are not associated so I'm slightly perplexed with the required nesting how I could achieve this.

What happends when a perform_async is called but sidekiq is not running?

Posted: 19 Jul 2016 07:21 AM PDT

I was wondering what happends when a perform_async is called on a worker but sidekiq (bundle exec sidekiq) isn't running ?

In my app I have some observers that ask sidekiq to do a job when one of my models is trigger (ie create, update or destroy in some cases).

I also have a rake task that builds me a database from some data I have.. When this task is running, it creates several records that trigger my observers who then push jobs in sidekiq queue.

For testing purpose I ran this task without turning on sidekiq and it's working fine, my data is being pushed in mysql !

I know ask myself what is happening to the job my observer tells my worker to do ? Is it still done ? Is it done but not asynchronously ? Is it not done ?

Possible to render and raise exception in Rails controller?

Posted: 19 Jul 2016 07:07 AM PDT

I have been fighting with this for some hours now. I have a controller action that I want to render a page and then raise an exception automatically. I couldn't find much information on this that makes me think that I am looking for the wrong thing.

Is something like the below possible?

class UsersController < ActionController::Base      def new      # .. do stuff      begin        UserMailer::send_confirmation_link(@user)      rescue StandardError => e        render 'email_error'        raise(e)      end      # .. other stuff    end    end  

In this case I simply want to inform the end-user of the error and then raise the exception on the application itself. Notice that I can't change the de-facto error page since this is a smaller application in the same codebase with a bigger application.

Is it possible to define permissions on specific resource attributes with cancan 1.6.5

Posted: 19 Jul 2016 06:54 AM PDT

In CanCan version 1.6.5

Is it possible to define permissions on specific resource attributes ?

For example, if I want to allow a user to only update the name and priority of a project, pass that as the third argument to can.

can :update, :projects, [:name, :priority]  

I want this functionality with rails-admin.

TypeError: can't dump MatchData

Posted: 19 Jul 2016 06:57 AM PDT

I've inherited an app from another developer and have added an error notification service, and have now received 1,408 occurrences of an error that I am having trouble getting to the bottom of...

The error is simply:

TypeError: can't dump MatchData

with only non-project frames in the stack trace....

I can see where this error is ultimately occurring in the activesupport gem message_verifier.rb file, but I assume that there's an error in the application or configuration that is causing it originally, and am not sure the best approach how to trace this back to its point of origin on our end. Strikes me as the kind of thing that someone may look at and immediately see recognize it. And advice appreciated....

This is the stack trace:

File "xxx/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.22.2/lib/active_support/message_verifier.rb" line 53 in dump  File "xxx/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.22.2/lib/active_support/message_verifier.rb" line 53 in generate  File "xxx/shared/bundle/ruby/1.9.1/gems/actionpack-3.2.22.2/lib/action_dispatch/middleware/cookies.rb" line 300 in []=  File "xxx/shared/bundle/ruby/1.9.1/gems/actionpack-3.2.22.2/lib/action_dispatch/middleware/session/cookie_store.rb" line 64 in set_cookie  File "xxx/shared/bundle/ruby/1.9.1/gems/rack-1.4.7/lib/rack/session/abstract/id.rb" line 335 in commit_session  File "xxx/shared/bundle/ruby/1.9.1/gems/rack-1.4.7/lib/rack/session/abstract/id.rb" line 211 in context  File "xxx/shared/bundle/ruby/1.9.1/gems/rack-1.4.7/lib/rack/session/abstract/id.rb" line 205 in call  File "xxx/shared/bundle/ruby/1.9.1/gems/actionpack-3.2.22.2/lib/action_dispatch/middleware/cookies.rb" line 341 in call  File "xxx/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.22.2/lib/active_record/query_cache.rb" line 64 in call  File "xxx/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.22.2/lib/active_record/connection_adapters/abstract/connection_pool.rb" line 479 in call  File "xxx/shared/bundle/ruby/1.9.1/gems/actionpack-3.2.22.2/lib/action_dispatch/middleware/callbacks.rb" line 28 in block in call  File "xxx/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.22.2/lib/active_support/callbacks.rb" line 405 in _run__656928281__call__438689938__callbacks  File "xxx/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.22.2/lib/active_support/callbacks.rb" line 405 in __run_callback  File "xxx/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.22.2/lib/active_support/callbacks.rb" line 385 in _run_call_callbacks  File "xxx/shared/bundle/ruby/1.9.1/gems/activesupport-3.2.22.2/lib/active_support/callbacks.rb" line 81 in run_callbacks  File "xxx/shared/bundle/ruby/1.9.1/gems/actionpack-3.2.22.2/lib/action_dispatch/middleware/callbacks.rb" line 27 in call  File "xxx/shared/bundle/ruby/1.9.1/gems/actionpack-3.2.22.2/lib/action_dispatch/middleware/remote_ip.rb" line 31 in   

Rails 5 Address already in use - bind(2) for "127.0.0.1" port 3000

Posted: 19 Jul 2016 07:25 AM PDT

After some coding got this error on running rails s:

Address already in use - bind(2) for "127.0.0.1" port 3000 (Errno::EADDRINUSE)  

My environment is:

$ rails -v         Rails 5.0.0  $ ruby -v  ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]  

I've tried:

  1. Create a new project - the same
  2. Checked Rails 4.2 - problem solved
  3. Reinstall rails 5 and ruby - the same problem
  4. lsof -wni tcp:3000 returns me nothing
  5. ps aux | grep "rails" - nothing
  6. ps aux | grep "puma" - nothing
  7. ps aux | grep "ruby" -nothing
  8. Use puma instead of rails s - problem solved

UPDATED

  1. Use RAILS_ENV=production bundle exec rails s - problem solved

Any suggestions?

Action cable not working I have to refresh both the tab to see message

Posted: 19 Jul 2016 06:42 AM PDT

Here is code of room.coffee :

App.room = App.cable.subscriptions.create "RoomChannel",    connected: ->     disconnected: ->       received: (data) ->      $('#messages').append "<p>#{data}</p>"          speak: (message) ->      @perform 'speak' , message: message  

cable.coffee :

@App ||= {}  App.cable = ActionCable.createConsumer()  

rooms.coffee:

$ ->      $messages = $('messages')      $messages.scrollTop $messages.prop('scrollHieght')      $('#message_input').focus()    $(document).on 'keypress','message_input','e'->      if e.keycode == 13 and e.target.value      App.room.speak(e.target.value)      e.target.value = ''      e.preventDefault()  

roomchannel:

class RoomChannel < ApplicationCable::Channel    def subscribed       stream_from "room_channel"    end      def unsubscribed      # Any cleanup needed when channel is unsubscribed    end      def speak(data)      message.create content: data['message']    end  end  

Broadcostmessage:

 def perform(message)      Actioncable.server.broadcast 'room_channel',render_message(message)    end    private    def render_message(message)      ApplicationController.renderer.render_message      end`enter code here`  

when create the new message it will not automatically load all the messages of my browser untill the page in not reload.

How do I apply bootstrap's clearfix to my code?

Posted: 19 Jul 2016 07:04 AM PDT

I'm using a wysiwyg editor in my project, and part of this editor includes the option to set images' position to left, right, inline. When I choose left, it gives it the float-left feature. I'm wondering how I can make it so the div containing my content automatically expands to allow for the floating images.

Below is my code for the posts partial I use in my project

<div class="thumbnail">    <div class="text">      <%= link_to post.title, post_path(post), class: "h1" %>      <p class="pull-right"><span class="glyphicon glyphicon-time"></span> Posted on <%= post.created_at.to_formatted_s :long %></p>      <hr>      <p><%= post.content.html_safe %></p><hr>      <p>        <% post.tags.any? %>          <div class="btn-group btn-group-xs" role="group" aria-label="...">            <% post.tags.each do |tag| %>                <%= link_to tag.name, tag_path(tag), class: "btn btn-info" %>            <% end %>          </div>      </p>    </div>  </div>  

Neo4jrb: a way to query for the model_class while doing collection_select

Posted: 19 Jul 2016 06:23 AM PDT

Is there a way to have a couple generic lines of code that can return results from the correct model_class based on the the model definition, and not on the lines of code?

Right now, I'm using a generator to create:

<%= f.collection_select(:semanticZoomOut, Class.all.sort { |a,b| a.name <=> b.name },    :id, :name, options = {      :prompt => "Please Select an Item",      :selected => @instance.semanticZoomOut.map(&:id)    }, html_options = {:multiple => true, :class=>"search"}) %>  

Where "Class" has to be manually changed for each _form.html.erb. Preferably, I'd like to generate something like this:

<%= f.collection_select(:semanticZoomOut, @instance.semanticZoomOut.class.all.sort { |a,b| a.name <=> b.name },    :id, :name, options = {      :prompt => "Please Select an Item",      :selected => @instance.semanticZoomOut.map(&:id)    },     html_options = {:multiple => true, :class=>"search"}) %>  

Ruby on Rails 5. Watch private videos amazon s3.

Posted: 19 Jul 2016 05:46 AM PDT

I trying to create a videos platform with RoR 5, and I want to use Amazon S3 to store the transcoded videos, that are exported directly from Transloadid. But I need only the registered users who payed a feed can watch (not download) the videos through my platform, but not by the url video.

Check Select year parameter

Posted: 19 Jul 2016 05:43 AM PDT

I have a select year which I wanna check if the year matches:

<%= select_year(Date.today, {start_year: 2015, end_year: Date.today.year} %>  

The default name is date[year] and I wanna compare the value in the query like:

where("YEAR(date) = ?", x)  

Where x would be the year, but I can't get it to work. I'm passing it from the controller like:

@result = Model.function(params[:date][:year])  

But I keep getting "undefined method `[]' for nil:NilClass" even though I see it passing "Parameters: {"utf8"=>"✓", "date"=>{"year"=>"2015"}}"

How to sort list using Angular Sortable and Rails

Posted: 19 Jul 2016 07:46 AM PDT

I'm stuck with this problem. I;ve built an API in Rails and a client in Angular. I've got a model called Todo which has a property called order. When I create a new Todo, I automatically assign the newly created todo a value order like so:

@todo = Todo.create(todo_params)  @todo.order = Todo.count + 1  

And to display all todos:

@todos = Todo.where(...).order(:order.desc)  

In my client I'm using Sortable for the UI manipulation and there's a method called onUpdate which gives me the new indexes for the array.

The problem I'm having is that the indexes are considerably different than the value I've in the order property. When the aforementioned function is called I get the item and two more values: newIndex and oldIndex, but the problem is that this doesn't give me the index of the other todos, so how can I reorganise this on the database?

I'd appreciate any help as I'm a bit at loss here.

PS: Please note this is Rails API only, so no views.

EDIT

Output wanted:

Let's imagine this: I have three items in the database: {name: A, order: 1}, {name: B, order: 2}, {name: C, order: 3}. In the front-end, while using ng-repeat, each item will have an $index. Let's say for argument sake that A will have $index value of 0, B 1, C 2. At the moment, when I use the Angular library Sortable, when I manually sort the list, I get the values: oldIndex and newIndex which corresponds to the position of the item I've moved within the array, but it does not shows the position of all items within array, so I don't know how to use the properties these values to update the object in the database.

No route matches {:action=>"/microposts", :controller=>"microposts", :params=>{:micropost=>{:content=>"Lorem ipsum"}}}

Posted: 19 Jul 2016 06:50 AM PDT

I am currently stuck on the rails tutorial from Michael Hartl (railstutorial.org), Chapter 13

and getting the following two errors:

1) Error:  MicropostsControllerTest#test_should_redirect_create_when_not_logged_in:  ActionController::UrlGenerationError: No route matches {:action=>"/microposts", :controller=>"microposts", :params=>{:micropost=>{:content=>"Lorem ipsum"}}}      test/controllers/microposts_controller_test.rb:11:in 'block (2 levels) in <class:MicropostsControllerTest>'      test/controllers/microposts_controller_test.rb:10:in 'block in <class:MicropostsControllerTest>'        2) Error:  MicropostsControllerTest#test_should_redirect_destroy_when_not_logged_in:  ActionController::UrlGenerationError: No route matches {:action=>"/microposts/499495288", :controller=>"microposts"}      test/controllers/microposts_controller_test.rb:18:in 'block (2 levels) in <class:MicropostsControllerTest>'      test/controllers/microposts_controller_test.rb:17:in 'block in <class:MicropostsControllerTest>'  

As far as i know, 'action' should be something like get, post, delete etc. But i don't know, why it says 'micropost' here.

Content of microposts_controller_test.rb:

require 'test_helper'    class MicropostsControllerTest < ActionController::TestCase      def setup      @micropost = microposts(:orange)    end      test 'should redirect create when not logged in' do      assert_no_difference 'Micropost.count' do        post microposts_path, params: {micropost: {content: 'Lorem ipsum'}}      end      assert_redirected_to login_url    end      test 'should redirect destroy when not logged in' do      assert_no_difference 'Micropost.count' do        delete micropost_path(@micropost)      end      assert_redirected_to login_url    end  end  

Content of micropost_controller.rb:

class MicropostsController < ApplicationController    before_action :logged_in_user, only: [:create, :destroy]      def create      @micropost = current_user.microposts.build(micropost_params)      if @micropost.save        flash[:success] = 'Micropost created!'        redirect_to root_url      else        render 'static_pages/home'      end    end      def destroy    end      private      def micropost_params      params.require(:micropost).permit(:content)    end    end  

Content of routes.rb:

Rails.application.routes.draw do    root 'static_pages#home'    get '/help' => 'static_pages#help'    get '/about' => 'static_pages#about'    get '/contact' => 'static_pages#contact'    get '/signup' => 'users#new'    get '/login' => 'sessions#new'    post '/login' => 'sessions#create'    delete '/logout' => 'sessions#destroy'    resources :users    resources :account_activations, only: [:edit]    resources :password_resets, only:     [:new, :create, :edit, :update]    resources :microposts, only:           [:create, :destroy]  end  

Any help is appreciated.

Thanks

Edit:

In micropost_controller_test.rb, it should've been:

class MicropostsControllerTest < ActionDispatch::IntegrationTest  

instead of

class MicropostControllerTest < ActionCntroller::TestCase  

Assiging values in Ruby using PHP equivalent for loop (I'm using Ruby on Rails)

Posted: 19 Jul 2016 05:28 AM PDT

I have a unsolved issue on stackoverflow which I suspect to be due to incorrect syntax of for loop on Ruby language.

I would like to ask what is the equivalent of the following in Ruby:

for ($x = 0; $x <= 10; $x++) {    $array[] = $x;  }  

Thanks in advanced for helping! Please help me solve my initial question in the link above. Many thanks!

Rails bootstrap delete confirmation with modal

Posted: 19 Jul 2016 06:05 AM PDT

I want to do a bevore action while clicking on a link. It should display a bootstrap modal with cancel and delete button.

code lookslike this:

Delete Button

<button class="btn btn-default" data-href="<%= url_for(:action => :delete, :id => @vid.id) %>" data-toggle="modal" data-target="#modalBox">              <i class="fa fa-trash"></i> <%= t "movies.add.delete" %>            </button>  

Modal Code is in application.html.erb -> modal is empty. I set the buttons on page load with jquery. that works fine.

    $(".modal-footer").html("<button type='button' class='btn btn-default' data-dismiss='modal'>Cancel</button> <a class='btn btn-danger btn-ok'>Delete</a>");  

and the code for the modal to wait is this:

$("#modalBox").on('show.bs.modal', function(e) {    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));  });  

whats my problem in this case?

I've got the code example from here: http://plnkr.co/edit/NePR0BQf3VmKtuMmhVR7?p=preview

thanks

Problem is: Modal is shown for less than 100ms ^^ .. and the deletion is performed

Rspec test got: nil

Posted: 19 Jul 2016 05:25 AM PDT

I'm trying to do a basic rspec test, which looks like this;

require 'rails_helper'      describe ReviewsController do      describe "GET #index" do     it "assigns a new review to @reviews" do     review = Review.create( rating: 4 )       get :index       expect(assigns(:review)).to eq([review])     assert_response :success    end   end  end  

But I'm getting the failure: expected: Review id: 8, rating: 4, created_at: "2016-07-19 11:58:28", updated_at: "2016-07-19 11:58:28", user_id: nil, game_id: nil got: nil

My ReviewsController looks like this:

class ReviewsController < ApplicationController      def index     @reviews = Review.all    end      def show     @review = Review.find(params[:rating])    end      def create     review = Review.new(review_params)       respond_to do |format|     if @review.save      format.html { redirect_to root_url, notice: 'Review was successfully updated.' }      format.json { render :show, status: :ok, location: @review }    else      format.html { render :new }      format.json { render json: @review.errors, status: :unprocessable_entity }     end    end   end      private      def post_params     params.require(:post).permit(:message)    end   end  

In case you need it, here's the review model:

class Review < ActiveRecord::Base   belongs_to :user   belongs_to :game   validates_presence_of :rating     validates_uniqueness_of :user_id  end  

I don't understand why it's asking for a user_id or game_id, because it's only about the reviews..

Devise authentication for polymorphic solution

Posted: 19 Jul 2016 05:19 AM PDT

Consider an application, which needs to have two different types of user:

  • User as in standard client
  • Organization as an entity offering some services through the application

Requirements:

  • different standard controllers (sessions, registrations etc)
  • access to different parts of the application of course

This seems like a walk in the park by simply creating two separate models with devise, but I really wouldn't like to duplicate so much functionality for authentication.

I went with a polymorphic association, where Organization and User are different models, both with a 1-1 relation with Entity representing authentication. Entity only has devise attributes (like password etc), while others have type-specific ones. Unfortunately this solution comes with a lot of drawbacks, like having to define custom helpers, warden strategies and devise failure apps.

I'm wondering, is there a concise solution for this type of issue?

Ideally, something like having two devise models delegating everything regarding authentication to a separate entity.

Rails has_and_belongs_to_many query for all records

Posted: 19 Jul 2016 05:26 AM PDT

Given the following 2 models

class PropertyApplication      has_and_belongs_to_many :applicant_profiles  end    class ApplicantProfile      has_and_belongs_to_many :property_applications  end  

I have a query that lists all property_applications and gets the collection of applicant_profiles for each property_application.

The query is as follows and it is very inefficient.

applications = PropertyApplication.includes(:applicant_profile).all.select |property_application| do      property_application.applicant_profile_ids.include?(@current_users_applicant_profile_id)  do  

assume @current_users_applicant_profile_id is already defined.

How can I perform one (or few) queries to achieve this?

I want to achieve something like this

PropertyApplication.includes(:applicant_profile).where('property_application.applicant_profiles IN (@current_users_applicant_profile))  

No comments:

Post a Comment