Thursday, August 11, 2016

Getting undefined method `acomments' for nil:NilClass error [on hold] | Fixed issues

Getting undefined method `acomments' for nil:NilClass error [on hold] | Fixed issues


Getting undefined method `acomments' for nil:NilClass error [on hold]

Posted: 11 Aug 2016 07:41 AM PDT

I am bulding a Question and Answer app where each Question has many answers and many comments. Each answer has many acomments (Answer comments).

I am getting undefined method `acomments' for nil:NilClass error.

Below is my Acomments Controller.

class AcommentsController < ApplicationController    def create          @question = Question.find(params[:question_id])          @answer = @question.answers.find(params[:answer_id])      @acomment = @answer.acomments.create(params[:acomment].permit(:username, :body))            redirect_to question_path(@question)      end  

AComment model:

class AComment < ApplicationRecord    belongs_to :answer    validates :body, presence: true, length: {minimum: 5}  end  

Answer model:

class Answer < ApplicationRecord      belongs_to :question      has_many :acomments, dependent: :destroy      validates :body, presence: true, length: {minimum: 5}  end  

Answers view:

<div class="answer clearfix">      <div class="answer_content">          <p class="answer_name"><strong><%= answer.username %></strong></p>          <p class="answer_body"><%= answer.body %></p>      </div>       <div id="comments">          <h2><%= @answers.acomments.count %> Comments</h2>          <%= render @answer.acomments %>          <h3>Add a comment:</h3>          <%= render "acomments/form" %>      </div>  </div>  

Could someone please tell me where I am making a mistake.

unicorn_rails command not found in shell script

Posted: 11 Aug 2016 07:37 AM PDT

I run unicorn_rails -c config/unicorn.rb -E production -D in my project directory, it's ok.

But when I use a shell script to run this command, get errors:

unicorn_rails: command not found  

my script:

#!/usr/bin/env ruby_executable_hooks  . /etc/init.d/functions  cd /data/projects/entos/current  unicorn_rails -c config/unicorn.rb -E production -D  action "start success" /bin/true  

Send ajax data from controller to view of another controller

Posted: 11 Aug 2016 07:43 AM PDT

I have a situation that I want to send data from "Relationships" controller to a view that belongs to "profile" controller.this system Is working but not the ajax section.I have to refresh the page each time that I want to see the results. Here is my code:

// relationships controller  class RelationshipsController < ApplicationController   def follow_user    @user = User.find_by! user_name: params[:user_name]    if current_user.follow @user.id      respond_to do |format|       format.html { redirect_to root_path }       format.js     end   end  end    def unfollow_user   @user = User.find_by! user_name: params[:user_name]   if current_user.unfollow @user.id     respond_to do |format|       format.html { redirect_to root_path }       format.js     end   end  end  end  

/profiles/show.html.haml

.posts-wrapper  .row.profile-header   .col-md-6     .img-circle       = profile_avatar_select(@user)    .col-md-6     .user-name-and-follow       %h3.profile-user-name         = @user.user_name         %span          - if @user == current_user           = link_to 'Edit Profile', edit_profile_path(@user.user_name),                                     class: 'btn edit-button'         - else          - if current_user_is_following(current_user.id, @user.id)            = link_to 'Following', unfollow_user_path,                                   remote: true,                                   class: 'btn unfollow-button',                                   id: 'unfollow-button',                                   method: :post          - else            = link_to 'Follow', follow_user_path,                                remote: true,                                class: 'btn follow-button',                                id: 'follow-button',                                method: :post    %p.profile-bio      = @user.bio    .user-statistics      %p        = pluralize @user.posts.count, 'post'      - @posts.each do |post|     = render 'posts/post', post: post  

// follow.js.erb (inside profiles folder)

$('#follow-button').attr('class', 'btn unfollow-button')                 .text('Following')                 .attr('href', "/<%= @user.user_name %>/unfollow_user")                 .attr('id', 'unfollow-button');  

// unfollow.js.erb (inside profiles folder)

    $('#unfollow-button').text('Follow')                           .attr('class', 'btn follow-button')                          .attr('href', "/<%= @user.user_name %>/follow_user")                          .attr('id', 'follow-button');  

Rails Form Object errors not persisted

Posted: 11 Aug 2016 07:31 AM PDT

Hi there I am trying to use the Form Object refactoring technique but I am having trouble getting the errors to stick. I have the following

class ProjectForm    include ActiveModel::Model    attr_reader :project,      def initialize()    end      def self.model_name      ActiveModel::Name.new(self, nil, "ProjectForm")    end      delegate :name,                     to: :project      def submit(params)      @project    = Project.new(params[:project])      if !@project.valid?        @project.errors.each do |f, e| # <----------------- this should add "Name must not be blank to ProjectForm instance, but it does NOT "          errors.add f, e      end    end  end    @project_form = ProjectForm.new.submit({project:{name:''}})  @project_form.errors.messages # []      BUT if I did a binding.pry to look into the method:     def submit(params)    @project    = Project.new(params[:project])    if !@project.valid?      @project.errors.each do |f, e| # <----------------- this should add "Name must not be blank to ProjectForm instance, but it does NOT "        errors.add f, e    end    binding.pry  end    # while in Pry:    errors.messages # {:name=>["Name must not be blank"]}>  

Do I have to include some other Rails specific libraries in order for this to work?

Thanks!

How would I go about allowing users to create surveys

Posted: 11 Aug 2016 07:42 AM PDT

Iv'e gotten myself into a bit of a brain mess up these past two days. I'd like to be able to allow my users to create a campaign (same concept as surveys), it will allow them to request certain data they wish such as an email address. This will then allow the person completing the form to proceed and receive a download link after entering an email. The email entered should be stored for the person who created the campaign to view.

Iv'e taken the approach with nested forms, however I ran into the trouble of allowing emails to be entered and saved for the campaign creator to view.

Any help is appreciated, thanks.

campaign.rb model

class Campaign < ActiveRecord::Base belongs_to :user has_many :queries accepts_nested_attributes_for :queries end

query.rb model

class Query < ActiveRecord::Base belongs_to :campaign has_many :results end

result.rb model

class Result < ActiveRecord::Base attr_accessible :content, :email, :query_id belongs_to :query end

schema.rb

  create_table "campaigns", force: :cascade do |t|  t.string   "title"  t.text     "description"  t.integer  "user_id"  t.datetime "created_at",  null: false  t.datetime "updated_at",  null: false   end      add_index "campaigns", ["user_id"], name: "index_campaigns_on_user_id", using: :btree      create_table "queries", force: :cascade do |t|  t.integer  "campaign_id"  t.text     "content"  t.string   "email"  t.datetime "created_at",  null: false  t.datetime "updated_at",  null: false  end      add_index "queries", ["campaign_id"], name: "index_queries_on_campaign_id", using: :btree      create_table "results", force: :cascade do |t|  t.integer  "query_id"  t.text     "content"  t.string   "email"  t.datetime "created_at", null: false  t.datetime "updated_at", null: false  end      add_index "results", ["query_id"], name: "index_results_on_query_id", using: :btree  

Part of campaign_controller.rb

  private  # Use callbacks to share common setup or constraints between actions.  def set_campaign    @campaign = Campaign.find(params[:id])  end    def campaign_params    params.require(:campaign).permit(:title, :description, :queries_attributes)  end    def query_params    params.require(:query).permit(:content, :email, :campaign_id)  end  

Invoke Flash Notice in Rails using [action].js.erb

Posted: 11 Aug 2016 07:44 AM PDT

I am trying to get the rails flash notice to appear within my application by using JavaScript only. I have a form which leverages remote: true to make an AJAX request to the controller when submitting. The form looks like the example shown below:

  # app/views/_email_register.html.erb    <%= simple_form_for :email, url: emails_path, remote: true do |f| %>      <div class="modal-body">        <div class="form-group">          <%= f.input :address, as: :email, placeholder: 'user@domain.com', label: false %>        </div>      </div>      <div class="modal-footer">        <%= f.submit 'Subscribe', class: 'btn btn-primary btn-block' %>      </div>    <% end %>  

The rails application was generated using rails-composer which also installed bootstrap css.

  # app/controllers/emails_controller.rb    def create      @email = Email.new(email_params)      respond_to do |format|        if @email.save          format.html { redirect_to :back, notice: 'Email was successfully registerd' }          format.js        else          format.html { render :new }          format.js        end      end    end  

The controller then invokes the create.js.erb as part of the respond_to block.

  # app/views/emails/create.js.erb    // flash to user it was successful    $(".alert").html("Email was successfully registered");  

The _messages.html.erb partial was automatically generated from rails-composer. Not sure if this partial can be invoked from the JavaScript

# app/views/layouts/_messages.html.erb  <% flash.each do |name, msg| %>    <% if msg.is_a?(String) %>      <div class="alert alert-<%= name.to_s == 'notice' ? 'success' : 'danger' %>">        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>        <%= content_tag :div, msg, :id => "flash_#{name}" %>      </div>    <% end %>  <% end %>  

Any assistance on how I can get the flash notice to show up via JavaScript would be much appreciated.

Rails nested form fields not displayed

Posted: 11 Aug 2016 07:11 AM PDT

I can't figure out what am I doing wrong in this simple nested form that it is not displaying nested fields.

Moreover if I change f.simple_fields_for :rfq_products do |rp| to f.simple_fields_for :rfq_product do |rp| I get the field comment rendered in the form but in the logs I get info Unpermitted parameter: rfq_product

Models

class Rfq < ActiveRecord::Base    has_many :rfq_products    accepts_nested_attributes_for :rfq_products  end    class RfqProduct < ActiveRecord::Base      belongs_to :rfq  end  

Controller

class RfqsController < ApplicationController  (...)      def rfq_params        params.require(:rfq).permit(:customtemplate_id, :supplier_id, rfq_products_attributes: [ :id, :_destroy, :comment ])      end  end  

View

<%= simple_form_for @rfq do |f| %>              <h3>Message template</h3>            <%= f.input :customtemplate_id, as: :select, collection: Supplier.find(s.supplier_id).customtemplates.map {|u| [u.code.to_s, u.id]}, include_blank: false %>        </div>          <h3>Products</h3>                <%= f.simple_fields_for :rfq_products do |rp| %>                  <%= rp.input :comment %>              <% end %>          <div class="form-actions">        <%= f.button :submit %>        </div>    <% end %>  

Nested query parameters in Swagger 2.0

Posted: 11 Aug 2016 06:59 AM PDT

I'm documenting a Rails app with Swagger 2.0 and using Swagger-UI as the human-readable documentation/sandbox solution.

I have a resource where clients can store arbitrary metadata to query later. According to the Rails convention, the query would be submitted like so:

/posts?metadata[thing1]=abc&metadata[thing2]=def  

which Rails translates to params of:

{ "metadata" => { "thing1" => "abc", "thing2" => "def" } }  

which can easily be used to generate the appropriate WHERE clause for the database.

Is there any support for something like this in Swagger? I want to ultimately have Swagger-UI give some way to modify the generated request to add on arbitrary params under the metadata namespace.

Functional testing devise user with custom roles ,rspec

Posted: 11 Aug 2016 06:54 AM PDT

I have user model with role field for user,admin and super admin which are in enum roles. I wrote function in controller_macros.rb for super admin sign in:

def login_super_admin    before(:each) do      @request.env["devise.mapping"] = Devise.mappings[:admin]      sign_in = FactoryGirl.create(:user, :super_admin)    end  end  

And i have this test:

context "As super admin" do    login_super_admin    it "renders new page" do      get :new      expect(response).to be_success    end  end  

This tests response code is 302, i can't figure out why, i think it never reaches controller new action, because i placed debugger to catch it. Why this happens?

Rails Timestamps UTC vs

Posted: 11 Aug 2016 07:30 AM PDT

I'm getting a failing rpsec test and it seems like it's a difference between the system clock and how Rails evaluates the time.

```

expected: 2015-01-01 15:00:00.000000000 -0800  got: 2015-01-01 15:00:00.000000000 +0000    (compared using ==)    Diff:  @@ -1,2 +1,2 @@  -2015-01-01 15:00:00 -0800  +2015-01-01 15:00:00 UTC  

```

For some reason Time.parse('01/01/2015 3:00pm') coerces the string into the timezone on the system clock. But the code is under test is outputting in UTC.

Does anyone know why or where this happens?

How can I stop Heroku Dyno that is running the Rails task through Heroku Scheduler?

Posted: 11 Aug 2016 07:12 AM PDT

Heroku Scheduler uses a One-off Dyno to run the scheduled task. That dyno doesn't appear in Heroku Dashboard, but it's there. How can I restart it, or temporarily stop it?

Rails: Toggle switch label helper

Posted: 11 Aug 2016 06:23 AM PDT

I have this toggle switch in HTML. What would be a clean Rails implementation for the form label?

<div class="can-toggle">      <%= form.check_box :running_profile %>      <label for="a">          <div class="can-toggle__switch" data-checked="Runner" data-unchecked="Walker"></div>      </label>  </div>  

Toggle Switch

I appreciate any help you can provide.

How to check rails application properly connected to MSSQL database or not

Posted: 11 Aug 2016 07:21 AM PDT

How to check rails application properly connected to MSSQL database or not(in controller/model)

Can anybody assist me on this?

Displaying currency symbols in form dropdown menu

Posted: 11 Aug 2016 07:30 AM PDT

I have a form in my real estate rails application where users can add a real estate listing.

In this create#apartment form, I'd like the user to be able to select (from a dropdown menu) what currency their pricing is in.

I've created a Currency model, views and a controller so the admin can add currency types. (I want the admin to be able to limit currency types).

Here is the currency migration file:

class CreateCurrencies < ActiveRecord::Migration    def change      create_table :currencies do |t|        t.string :name        t.string :symbol          t.timestamps null: false      end    end  end  

(The "symbol" being a string that holds the currency HTML code)

I connected Currency and Apartment with a belongs_to/has_many relationship in the db. I then implemented a dropdown menu in the create#apartment form where users can select the currency.

My question is, how can I display the currency symbol in the dropdown menu?

Here's what I tried.

<%= f.collection_select :currency, Currency.order(:name),:id, "#{:symbol}".html_safe %>  

The problem is, this doesn't display the currency symbols as I would have hoped; it just displays the string that was entered (the currency HTML code).

For example, with the code as it is, if an Admin entered the currency HTML code for $ (&#36), the dropdown shows "&#36" isntead of the expected "$")

Thanks in advance!!

Add a new action to existing controller or add a new action to a new controller?

Posted: 11 Aug 2016 07:27 AM PDT

RoR4 app. I have a page X which shows pricing stuff in an eCommerce website. So there is a pricing controller with index page showing the pricing content. There is a purchase button which needs to do following things:

  1. If clicked, check whether the user is authenticated
  2. If authenticated, take them to third party services for credit card information
  3. On successful purchase, redirect the flow back to original eCommerce site

My dilemma: Should I add a new purchase controller? or add a new method purchase in existing controller of pricing.

Sending CSV attachment with action mailer & AWS Sqs queue

Posted: 11 Aug 2016 05:44 AM PDT

I am trying to send an email with a CSV attachment from a Rails AWS EB application (worker tier).

This example will send the email correctly with the data attached, I have hardcoded the CSV string here;

def send_mail      content = "Example,CSV,Content\n,..."      attachments['test.csv'] = { mine_type: 'text/csv', content: content}      mail(   :from => 'test@mail.com>',               :to => 'person@mail.com',               :subject => 'Email with attachment',               :body => "testing sending email attachment"          )  end  

However when I send the CSV string from the API I seem to have an encoding problem. The object I am sending is this;

email = {      from: "test@mail.com",      to: "person@mail.com",      subject: "Email with attachment",      content_type: 'text/html',      attachments: {          filename: 'test.csv',          content: File.read("#{Rails.root}/test.csv")      }  }  

And the method;

def send_mail(params)      filename = params[:attachments][:filename]      attachments[filename] = {   mine_type: 'text/csv',                                   content_type: 'text/comma-separated-values',                                   transfer_encoding: '7bit',                                  content: [:attachments][:content]                              }      mail(params)  end  

I think there may be a problem with the transfer_encoding, If I do not set it to '7bit' the content is base64 encrypted. I have used the action mailer method attachments.instance_values to check the content_encoding of the email that works and its binary, however it I set it as binary in the failing example it reverts to base64. If I set the params[:attachments][:content] as a variable then when I log the attachments.instance_values the value is 'binary' but when the mail is received the message is;

 ----==_mimepart_57ac6ae25a220_68972ad836f669fc984a7       Content-Type: text/comma-separated-values; charset=UTF-8       Content-Transfer-Encoding: base64       Content-Disposition: attachment;       filename=test.csv       mine-type: text/csv       Content-ID: <57ac6ae259b90_68972ad836f669fc983b0>  

any help or suggestions appreciated.

What is difference between scheduled_delivery_date, actual_delivery_date, ship_time in active_shipping gem

Posted: 11 Aug 2016 05:39 AM PDT

I am using active_shipping gem to integrate shipment tracking from Fedex and UPS. I want to get the estimated time by when the package will be delivered.

Tracking response from active_shipping contains of scheduled_delivery_date, actual_delivery_date and ship_time.

I am unable to find documentation on above terms.

From the name I can guess that scheduled_delivery_date is the estimated delivery date when package will be delivered to the said address and actual_delivery_date is the exact date on which the package was delivered. Also I have no clue about ship_time.

I have another concern too, when I try to test fedex by using test tracking number it returns nil for scheduled_delivery_date and actual_delivery_date.

Extra Info:

Tracking number that I tested with have 11 shimpent_events and last one is delivered event, so i expect tracking response to have scheduled_delivery_date and actual_delivery_date.

Delivered shipment event shows date of 'Thu, 09 Jan 2014', while ship_time is show as 'Mon, 01 Aug 2016'

fedex = ActiveShipping::FedEx.new(login: '1*****', password: 'qOa2x****', key: '0TC****', account: '510****', test: true)    tracking_info = fedex.find_tracking_info('122816215025810')  

Is this happening because I am using fedex in test mode. Will everything be fine in production mode? Can anyone please help me to understand or point me to documentation which explains scheduled_delivery_date, actual_delivery_date and ship_time. Thanks :)

Rails: Redirect form_tag with radio button to 'show' page

Posted: 11 Aug 2016 05:35 AM PDT

I'm a rails noob, and no matter what I do, when I use my radio button I can't get it to redirect to where I want.

In short, I want to "show" the post id that the user has radio clicked when he clicks the submit button.

My feeble attempt so far is this (_searchresults.html):

<%= form_tag posts_path(:post_id), method: 'get' do %>  

And then my radio button:

<td><%= radio_button_tag :post_id, post.id %></td>  

And my submit_tag:

<%= submit_tag "Select Post", :name => nil, class: "button" %>  

I want clicking that submit tag to go to this url:

localhost:3000/posts/10

^^^ where "10" is the post id of whatever post was clicked on the radio button.

Instead, it's going to this url:

localhost:3000/posts.post_id?utf=.&post_id=10

^^^^where utf equals a checkmark, not a dot, but I couldn't type that in

I don't understand why it won't go the URL I want.

kaminari show current page + 5 links

Posted: 11 Aug 2016 05:06 AM PDT

I have a rails application where I am using kaminari.

I have following code in a partial

= paginate hotels, :remote => true  

When on first page it shows links 1 to 5 eg: 1 2 3 4 5 ..>

Then if I go to 5th page it shows like this < 1 2 3 4 5 6 7 8 9 … >

What I want to do is show current page plus next 5 pages links.

eg. If I am on page 10 I should see < 10 11 12 13 14 15 ..>

Does anyone know if this is possible ?

How to make devise gem go to specific page when user logs in for the FIRST time using confirmation email link but only in this situation

Posted: 11 Aug 2016 05:07 AM PDT

so i am trying to build a social network for rails practise that using devise gem asks the user to confirm email in order to enable login.

My problem: I want the user to fill a form when he/she logs in for the very first time. This first time happens when they click on the link in the confirmation email.

All the other times the user logs in goes to a different page.

How can I do this?

Sorcery Simple Login with username

Posted: 11 Aug 2016 04:30 AM PDT

I'm working on a blog website written in RoR and got stuck on a problem with Sorcery. I did the tutorial from their documentation to create the simple login. My problem is, that they use email to identify the user at the login.

So I tried to modify my session controller to send the username as parameter instead of email and modified my view accordingly.

The log says that everything works fine and the username and password is passed to the database. But, and I can't find a solution to that, the SQL string that's generated still uses "authors"."email" as parameter.

How can I fix that?

My log:

Processing by AuthorSessionsController#create as HTML  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ForXjJMiPCI6H37xqtPzGwa9XBOHx1yIaGjlZdUd6Iw+G4M5v6s/JXrFcGG5VVyuFl6Is+cr5Zp/fxJcNyS/Tw==", "username"=>"Test", "password"=>"[FILTERED]", "commit"=>"Login"}  Author Load (0.5ms)  SELECT  "authors".* FROM "authors" WHERE "authors"."email" = 'Test' ORDER BY "authors"."id" ASC LIMIT ?  [["LIMIT", 1]]  Rendering author_sessions/new.html.erb within layouts/application  Rendered author_sessions/new.html.erb within layouts/application (2.4ms)  Completed 200 OK in 63ms (Views: 49.6ms | ActiveRecord: 2.5ms)  

My session controller:

class AuthorSessionsController < ApplicationController    def new    end      def create      if login(params[:username], params[:password])        redirect_back_or_to(articles_path, notice: 'Logged in successfully.')      else        flash.alert = 'Login failed.'        render action: :new      end    end      def destroy      logout      redirect_to(articles_path, notice: 'Logged out!')    end  end  

My new.html.erb

<h1>Login</h1>    <%= form_tag author_sessions_path, method: :post do %>  <div class="field">    <%= label_tag :username %>    <%= text_field_tag :username %>    <br>  </div>  <div class="field">    <%= label_tag :password %>    <%= password_field_tag :password %>    <br>  </div>  <div class="actions">    <%= submit_tag 'Login' %>  </div>  <% end %>    <%= link_to 'Back', articles_path %>  

Move views javascript code to javascript files

Posted: 11 Aug 2016 07:45 AM PDT

First let me tell you that I've searched for this and didn't manage to find any answer for my problem.

I have a lot of Javascript on my layouts/application.html.haml file:

### at the end of application.html.haml file    - if @instance_variable.condition        :javascript          // a lot js/jQuery code        :javascript          // more js code that uses #{ @instance.vars }        - if @another_condition.using.ruby.cody            :javascript              // more js code that uses #{ @instance.vars }  

And I'm using instance vars within this code, which means that this vars will only be declared on the controller (application controller). As this is the application layout, these scripts run on every page of my website (and that's what I need of course).

What I want is to move all this code to a js.erb file (or .haml if possible). First - because is easier to manage this code in a separate file; Second - because I don't want to have <script> // a lot of js code </script> tags at the end of every html file, I want to have a <script async src='link'/> tag only.

Also I'm including already the application.coffee at the beginning of the file, but I need this script tag at the end of the html files.

Rails forms, change field name dynamically with iteration variable?

Posted: 11 Aug 2016 04:21 AM PDT

I have an iteration for all my locales.

I want the :text and :title field on every iteration to change depending on the locale, for example :title_en for English, :title_ru for Russian, :title_gr for Greek and so on.

The "en", "ru", "gr" and so on are the locale in my iteration so I get them from there.

<% I18n.available_locales.map.with_index(1) do |locale, index| %>     <%= f.text_field :title_(I want to use the locale here) %>  <%end%>  

How do I go about that? What is the best way to do it?

Modifying create method for nested form model

Posted: 11 Aug 2016 04:13 AM PDT

I have a Project scaffold in which i wanted to create nested forms for a model called Task, the project has many tasks and each task belongs to a project. when the user is creating the Project he can dynamically add tasks. for this I'm using the cocoon gem.
What I want to do is have certain actions happen for every task that gets created, so what I need to do now is simply modify the create method for Task.
since the cocoon tutorial had you create only a model for Task, i destroyed the model and generated a scaffold to get the controller ( i also tried to only generate the scaffold_controller ) and modified the create method there, but it seems that the program does not go through that create method.

I'm aware that you can approach this by doing something like @project.tasks.each do |t| inside the Project's create method, but I was wondering if there is a way through which I can modify the controller methods for Task the way I can modify them for any non-nested controller.

Rails 4.2 STI // Wrong casting (Superclass instead of Subclass)

Posted: 11 Aug 2016 04:12 AM PDT

I'm trying to implement an STI pattern in my Rails application and I'm going to get crazy.

I have three models:

Superclass:

class Reservation < ActiveRecord::Base      self.inheritance_column = :inheritance_type        #some code here  end  

Subclasses:

class ApartmentReservation < Reservation      #some code here  end    class StorageReservation < Reservation      #some code here  end  

I want to get a Subclass instance, calling Superclass, e.g.

Reservation.all should return a collection of ApartmentReservation and StorageReservation, but it returns a collection of Reservation.

I've been looking for an answer and I found out it's because of an eager load in a development environment. Following the advices, I've been trying with these parts of code:

In initializers:

Rails.configuration.to_prepare do    require_dependency 'app/models/apartment_reservation'    require_dependency 'app/models/storage_reservation'  end  

In Superclass:

def self.descendants      [ApartmentReservation, StorageReservation]  end  

In the bottom of Superclass:

require_dependency 'app/models/apartment_reservation'  require_dependency 'app/models/storage_reservation'  

But it still doesn't work.

Has anyone any idea, how to make it work?

This concerns rails server, however in rails console everything works fine.

Axlsx in Rails: rendering formula issue

Posted: 11 Aug 2016 06:35 AM PDT

When I pass formula to add_row, it always returns it with additional sign ' at the beginning. As result the formula is not calculated but rendered like a text in Excel file.

For example: Method sheet_quests.add_row ["=SUM(D7:D8)", "=D7-D8", "=D7"] returns

'=SUM(D7:D8)  '=D7-D8  '=D7   

I need to have the result of calculated formula, not a text.

Any ideas?

Is there a way to combine where and where.not into one condition in Rails?

Posted: 11 Aug 2016 03:56 AM PDT

I have an Event model, that has user_id inside it. I want to select all objects of this model, with specified user_id but not including specific events. So I can do it with a query like that:

Event.where(user_id: user.id).where.not(id: id)  

But can I combine these 2 where functions into one?

I know that if I need to find, for example, events with specified ids and user_ids, I can do it this way:

Event.where(user_id: user_id).where(id: id)  

and I can compact it using one where call instead of two:

Event.where(user_id: user_id, id: id)  

but can I do the same thing if I am using where and where.not?

Is it possible to cross reference FB taggable_friends and local user records under API v2?

Posted: 11 Aug 2016 03:43 AM PDT

I am using Koala in a Rails app to get a user's friends for a simple tagging interface.

Some time back, Facebook changed the API (v2.0) such that this end point now returns a hashed ID, rather than the friend's FB ID. I've just started working with this endpoint for the first time since the change and am wondering, is it still possible to correlate an FB taggable_friends with a user of my app.

For example, within my app a user creates an event she attended, and now wants to tag friends she was with. The taggable_friends API allows taggings to be pushed to FB, but how do I also represent that tagging within my app?

The taggable_friends endpoint returns basic details such as name and avatar, so I could just store and display those. But if the friend is also a user of my app, and perhaps has a different avatar here, I'd like to display the details they have set in the app rather than FB details.

Is there any way to cross reference taggable_friends with local user records under the new API?

Rails group_by and sorting upon field in related model

Posted: 11 Aug 2016 03:44 AM PDT

I have a User that belongs to a User_type. In the user_type model, there's a field called position to handle the default sorting when displaying user_types and their users.

Unfortunataly this does not work when searching with Ransack, so I need to search from the User model and use group_by to group the records based on their user_type_id.

This works perfectly, but I need a way to respect the sorting that is defined in the user_type model. This is also dynamic, so there's no way of telling what the sorting is from the user model.

Therefor I think I need to loop through the group_by array and do the sorting manually. But I have no clue where to start. This is the controller method:

  def index      @q = User.ransack(params[:q])      @users = @q.result(distinct: true).group_by &:user_type    end  

How do I manipulate that array to sort on a field that in the related model?

Does Rails streaming need to finish template generation to output the template?

Posted: 11 Aug 2016 03:19 AM PDT

I've been setting up Rails streaming. I have it working so that the top of the layout is rendered immediately, but when it outputs the template, it seems to process the whole template before flushing it.

e.g. Let's say I have a standard layout with etc, then I have a template like this, with a simulated pause in the middle:

content start  <% sleep 5 %>  content end  

Now when I curl this, I will see:

<html>    <head>       <title>test</title>    </head>    <body>      (.. 5 seconds later ..)         content start       content end    </body>  </html>  

Is this expected behaviour? I thought it would render the template as it's being processed. (Hamlit is the template engine, if that matters.)

No comments:

Post a Comment