Tuesday, October 25, 2016

How can I destroy a record in a join table with has_and_belongs_to_many association? | Fixed issues

How can I destroy a record in a join table with has_and_belongs_to_many association? | Fixed issues


How can I destroy a record in a join table with has_and_belongs_to_many association?

Posted: 25 Oct 2016 07:45 AM PDT

I am creating an app where a user can favorite a room. I accomplished this with a has_and_belongs_to_many association. I chose this instead of has_many :through because this requires a third model (which could be Favorite) and it would only be used to create the association.

How can I add a unfavorite(destroy) action into the view or controller?

rooms_controller.rb

def favorite      room = Room.find(params[:id])      current_user.rooms << room unless current_user.rooms.exists?(room)      redirect_to wishlist_path  end  

routes.rb

post 'rooms/:id/favorite' => 'rooms#favorite'  

show.html.erb (room)

<div>Add to Wishlist</div>  <%= form_tag(controller: "rooms", action: "favorite", method: "post") do %>      <%= submit_tag "Favorite"%>  <% end %>  

wishlist.hmtl.erb

<% current_user.rooms.each do |room| %>      <%= room.listing_name %>  <% end %>  

Description not available because of robots.txt on rails app

Posted: 25 Oct 2016 07:39 AM PDT

I have some problems with the google snippet description of my rails app in google search results. I get :

A description for this result is not available because of this site's robots.txt   

I dont understand why I am getting this. I am not blocking the googlebot. Here's my robots.txt

User-Agent: *  Disallow: /admin/  Sitemap: https://s3-eu-west-1.******  

and I also include this meta in my application.html file :

%meta{ name: 'description', content: "Le prix national Stars et Métiers est organisé en collaboration entre le groupe Banque Populaire et le réseau des CMA pour encourager l'excellence, l'audace et l'innovation, et mettre en lumière des chefs d'entreprises d'exception" }/  

Why does google not want to take into account my description ?

UPDATE :

when I am using this tool to see if my description is displaying, it works :

https://totheweb.com/learning_center/tool-test-google-title-meta-description-lengths/

but when I try to find the website via the classic google search, I still get A description for this result is not available because of this site's robots.txt

How to resolve relations in a query for JSON

Posted: 25 Oct 2016 07:47 AM PDT

I have 2 tables, Jedis and Padawans, with a many to many relationship through a third table, Apprenticeship. their app/models rb files define their relations like this:

Jedi:

class Jedi < ActiveRecord::Base    attr_accessible :name    has_many :apprenticeships    has_many :padawans, :through => :apprenticeships  end  

Padawan:

class Padawan < ActiveRecord::Base    attr_accessible :name    has_many :apprenticeships    has_many :jedis, :through => :apprenticeships  end  

Apprenticeship:

class Apprenticeship < ActiveRecord::Base    attr_accessible :jedi_id, :padawan_id    belongs_to :jedi    belongs_to :padawan  end  

When I query like this:

@apprenticeships = Apprenticeship.where(jedi_id: 1)  

And return the results to the front-end as JSON:

respond_to do |format|    format.json { render json: @apprenticeships }  end  

The JS ajax call that initiated the request receives an array of objects, each representing an apprenticeship record. Each object looks like this (stringified):

"{"id":1,"created_at":"2016-10-25T04:42:24.020Z","updated_at":"2016-10-25T04:42:24.020Z","jedi_id":1,"padawan_id":1,"apprenticeship_status":null}"  

At this point in the process, I would prefer the apprenticeship records to be this instead (with ids resolved to objects):

"{"id":1,"created_at":"2016-10-25T04:42:24.020Z","updated_at":"2016-10-25T04:42:24.020Z","apprenticeship_status":null,"jedi":{"id":1,"name":"Yoda"},"padawan":{"id":1,"name":"Luke Skywalker"}}"  

What is the correct, cleanest method of accomplishing this using only Ruby - so JS can receive the proper array of objects to work with?

Thanks for your help.

Sending mail, getting ActionView::MissingTemplate <path> with 'mailer'

Posted: 25 Oct 2016 07:29 AM PDT

When trying to send emails with Sidekiq, I am getting this error

ActionView::MissingTemplate: Missing template campaign_mailer/hugh_email with "mailer". Searched in: * "campaign_mailer"

In the controller

CampaignMailer.hugh_email(email, user).deliver_later  

In campaign_mailer.rb

layout 'mailer'    def hugh_email(email, user)      mail(to: @user.email, subject: email.subject)  end  

app/views/campaign_mailer/hugh_email.html.slim has the html, and I have a template in layouts/mailer

Note: I have tried everything I can find, even re-generated mailers. It seems to work with a new mailer when I send with deliver_now, but as soon as I try deliver_later the error returns (even when going back to trying a deliver_now).

Route all subdomains to my Heroku Rails app

Posted: 25 Oct 2016 07:39 AM PDT

I register my domains with DNSimple. My app is hosted on Heroku.

How can I arbitrarily route all subdomains to my Heroku app?

Example

  • bluejays.cappedin.com
  • redsox.cappedin.com
  • anything.cappedin.com

No matter what the user types as the subdomain (always just 1 level deep) I want it routed to my heroku app. Ideally I don't want to define every single subdomain in Heroku or DNSimple... it should just direct everything.

Any and all subdomains are just routed to my app where I handle the logic of what to do with request.subdomain method.

Will having these "foul" up what I am trying to do (below) enter image description here

Thanks!

Random No route matches [GET] "/" error with a working root_path

Posted: 25 Oct 2016 07:29 AM PDT

I randomly see a No route matches [GET] "/" error in the logs of an app. Here is the output.

[LG53P2]2016-10-25 02:46:20 +0000 severity=FATAL, ActionController::RoutingError (No route matches [GET] "/"): FATAL  [LG53P2] actionpack (4.2.7.1) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'  [LG53P2] actionpack (4.2.7.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'  [LG53P2] railties (4.2.7.1) lib/rails/rack/logger.rb:38:in `call_app'  [LG53P2] railties (4.2.7.1) lib/rails/rack/logger.rb:22:in `call'  [LG53P2] actionpack (4.2.7.1) lib/action_dispatch/middleware/request_id.rb:21:in `call'  [LG53P2] rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'  [LG53P2] rack (1.6.4) lib/rack/runtime.rb:18:in `call'  [LG53P2] activesupport (4.2.7.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  [LG53P2] actionpack (4.2.7.1) lib/action_dispatch/middleware/static.rb:120:in `call'  [LG53P2] rack (1.6.4) lib/rack/sendfile.rb:113:in `call'  [LG53P2] actionpack (4.2.7.1) lib/action_dispatch/middleware/ssl.rb:24:in `call'  [LG53P2] skylight (0.10.5) lib/skylight/middleware.rb:61:in `call'  [LG53P2] railties (4.2.7.1) lib/rails/engine.rb:518:in `call'  [LG53P2] railties (4.2.7.1) lib/rails/application.rb:165:in `call'  [LG53P2] puma (3.4.0) lib/puma/configuration.rb:224:in `call'  [LG53P2] puma (3.4.0) lib/puma/server.rb:569:in `handle_request'  [LG53P2] puma (3.4.0) lib/puma/server.rb:406:in `process_client'  [LG53P2] puma (3.4.0) lib/puma/server.rb:271:in `block in run'  [LG53P2] puma (3.4.0) lib/puma/thread_pool.rb:114:in `call'  [LG53P2] puma (3.4.0) lib/puma/thread_pool.rb:114:in `block in spawn_thread'  

The app is private and used by a really small number of people and none of the users have experienced this error ( not able to access the root_path ). I never see it outside the logs. I assume this could be a bot doing a scan.

The routes.rbfile contains the right information:

constraints subdomain: "the_subdomain" do          scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do        root to: 'my_controller/static#home'      end        .... other routes    end  

And the rake routes output seems normal:

root GET /(:locale)(.:format) my_controller/static#home

At this point the app is regularly used and this bug is just a glitch in the logs nothing more. But I think it worth asking!

Any idea about what can cause this error and how or if I can do something about it?

Getting error Faraday::ClientError: the server responded with status 400 on adding a share to linkedin in rails

Posted: 25 Oct 2016 06:48 AM PDT

I am trying to add a share using linkedin-oauth2 gem and getting an error

Faraday::ClientError: the server responded with status 400  

I have also tried from irb but still getting same error. I have w_share permissions set for my access token but I don't know why I am getting this error. Here is a snippet of what m doing in my controller method->

def post_on_linkedin    user = User.find_by_id(session[:user_id])    @client = LinkedIn::API.new(user.token)    @client.add_share(content: "hello")    redirect_to social_media_linkedin_index_path  end  

Please tell me if something is wrong with my syntax or anything else and please provide the syntax for using 'add_share' method with all other options. Thanks

DRY views strftime call

Posted: 25 Oct 2016 07:40 AM PDT

I have a view of my model with many date fields rendered.

What I want to do is call strftime('%d.%m.%Y %H:%M') on each date field I have.

- @items.each do |item|     = item.date_field.strftime('%d.%m.%Y %H:%M')     = item.date_field1.strftime('%d.%m.%Y %H:%M')  

Any ideas on how I can to DRY this? I tried to make to_s method in my model, but unfortunately that doesn't work.

Update:

I defined this method:

def to_s(date)    send(date).strftime('%d.%m.%Y %H:%M')  end  

So I can:

- @items.each do |item|     = item.to_s(:date_field)    = item.to_s(:date_field1)  

has_many after a has_many :through?

Posted: 25 Oct 2016 06:34 AM PDT

Here are my current models...

class Artist < ApplicationRecord    has_many :albums    has_many :follows    has_many :users, -> { uniq }, through: :follows  end    class Album < ApplicationRecord    belongs_to :artist  end    class Follow < ApplicationRecord    belongs_to :artist    belongs_to :user  end    class User < ApplicationRecord    has_many :follows    has_many :artists, -> { uniq }, through: :follows  end  

What I want to be able to do is get all the Albums for a user.

I can get the artists easily (@user.artists) but what I'm having trouble getting are all the albums of those artists.

Artists are associated with Users through the Follows model.

Would love to be able to do something like @users.albums or @users.artists.albums.

Fullcalendar rails: wrongly displaying events sources

Posted: 25 Oct 2016 06:24 AM PDT

I've fullcalendar working in Rails with postgresql. I've a model 'Event' with which i'm trying to feed the calendar using eventSources. The problem is that when the calendar is displayed shows the events with the current date and time, not with the corresponding time and date of the events.

I've been looking at these questions, which I think is related to my problem. But I have not found how to fix it yet.

The code that I have so far:

Event controller

def index    @events = Event.all    respond_to do |format|      format.html # index.html.erb      format.json { render :json => @events }    end  end  private    def set_event      @event = Event.find(params[:id])    end        def event_params      params.require(:event).permit(:title, :start_time, :end_time)    end  

JavaScript

$('#calendar').fullCalendar({              editable: true,            eventLimit: true,            eventSources: [{                url: '/events'            }]  });  

I must confess I am new to Ruby, so it may be that I'm missing something basic (most likely).

Thanks!

How to select new_station where ST_DWithin(PostGIS) in rails

Posted: 25 Oct 2016 05:51 AM PDT

My table is

create_table :infomaps do |t|      t.string :name_station      t.string :name_location    t.integer :waterlevel    t.integer :rain    t.integer :water_sealevel    t.integer :tropical_level    t.integer :bank_level    t.string :river_name    t.string :place        t.st_point :lonlat, geographic: true    t.integer :time      t.timestamps null: false  end  

I want to use Example code

SELECT name FROM nyc_streets WHERE ST_DWithin(      geom,      ST_GeomFromText('POINT(583571 4506714)',26918),      10    );  

result name:Wall St, Broad St and Nassau St

but I use in ruby on rails

    @result = Infomap.find_by_sql("SELECT name_station FROM infomaps    WHERE ST_DWithin(lonlat,      ST_GeomFromText('POINT(20 100)',26918),      100); ")  

it error

PG::InvalidParameterValue: ERROR: Only lon/lat coordinate systems are supported in geography. : SELECT name_station FROM infomaps WHERE ST_DWithin(lonlat, ST_GeomFromText('POINT(20 100)',26918), 100);

How to use ST_DWithin and others PostGIS functions in rails

Rails Form: How to handle multiple selections in drop-down menu

Posted: 25 Oct 2016 05:41 AM PDT

I've been playing around with my form where I have a drop-down menu where you can select multiple options:

f.select :hobbies, [                      ['First First First First','1'],                      ['Second Second Second Second','2'],                      ['Third Third Third Third','3'],                      ['Fourth Fourth Fourth Fourth','4'],                      ['Fifth Fifth Fifth Fifth','5'],                      ['Sixth Sixth Sixth Sixth','6'],                     ],                     {},                     {:multiple => true}  

But I'm so confused at what the heck this thing is putting into my hobbies attribute (which is a string).

When I print out the contents after selecting the first three options:

<%= @user.hobbies %>  

I get this junk:

--- - '' - '1' - '2' - '3'  

So clearly it's getting the '1', '2', and '3' that I selected, which is good. But the rest of the output is weird looking.

All that I want to do is be able to print '1', '2', and '3' (or whatever options were selected). Of course, I could parse these values out of the giant string based on it's dash-separated format, but that seems the wrong way to do it.

I saw something about turning "hobbies" into an array by making it "hobbies[]", but that gives the odd error:

(wrong number of arguments (0 for 1..2))  

So how exactly am I supposed to handle this stuff internally?

How to send reset password instead of confirmation email in Devise?

Posted: 25 Oct 2016 05:36 AM PDT

I am trying to make it so that if a one type of User is created - then instead of sending the confirmations email, it sends the reset password link (I have already achieved so that the reset password link serves as both confirmation and reset password). This is basically a try to avoid duplication of emails since I allow creating a user without password so that the user then can request his first password via reset password.

I am trying to override the Confirmations Controller like so:

class Users::ConfirmationsController < Devise::ConfirmationsController      def create      if self.resource.encrypted_password.empty? then        Users::PasswordsController.create      else        super      end    end    end  

And in routes:

devise_for :users, controllers: {     passwords: 'users/passwords',     sessions: 'users/sessions',    confirmations: 'users/confirmations',    omniauth_callbacks: 'omniauth_callbacks'  }  

The overriding works with other models. But the create action in confirmations controller is never called. I put a lot of byebug statements all around the Gem itself, and it seems even the original create action is not called, but the email is sent anyway. I am using sidekiq for delayed emails. The only place that is run seems to the mailer:

def confirmation_instructions(record, token, opts={})    byebug # <- it does stop here    @token = token    devise_mail(record, :confirmation_instructions, opts)  end  

But when I check the stack trace, it looks like it's called from some labda function.

The question: why isn't devise using ConfirmationsController and how do I achieve the task at hand?

Thanks a lot!

JSON to insert in Rails

Posted: 25 Oct 2016 06:47 AM PDT

I'm new to Rails.

I need to insert the JSON response into my database.

The response received is:

{  "entity_name":"Test company",  "entity_relation":"2",  "address1":  {  "street_address":"street address for test company",  "city":"Test city",  "province":"Test province",  "postal_code":"411015"  },  "address2":  {  "street_address":"",  "city":"",  "province":"",  "postal_code":""  },  "phone_number":["1231231230"],  "entity_website":"www.testsite.com",  "entity_email":"a1@b1.com",  "entity_description":"This is the test description",  "controller":"frontend",  "action":"createorganization"  }  

address is a separate table. How can I get:

address1[street_address]  address1[city]  address1[province]  address1[postal_code]  

so I can insert in the database?

I did:

data = JSON.parse data  render json: data["address1"]  

It outputs:

{  "street_address":"street address for test company",  "city":"Test city",  "province":"Test province",  "postal_code":"411015"  }  

How to integrate a bootstrap file with existing Rails application in cloud 9? [on hold]

Posted: 25 Oct 2016 05:18 AM PDT

I have an exciting Rails application in cloud 9 and a bootstrap file in my laptop. I want to integrate the bootstrap file with the rails application in cloud9.

How to generate a html file from a template in a controller and upload it via paperclip in Rails 4

Posted: 25 Oct 2016 05:11 AM PDT

I appreciate my question should be divided in two, however both are too intimate related not to have them together here.

Please note that I'm using Ruby 2.3.1, Rails 4.2.7 and Mongoid 4.

I need to generate a HTML file from a template and upload it to S3. In my App I'm already using Paperclip, so I'm sticking with it, if possible. I know that ideally I shouldn't mix views within controllers, but it seems in this case, I have no alternatives.

In my Model I have the following:

has_mongoid_attached_file :widesky,      :path           => 'path/where/to-store/file',      :url            => ':s3_domain_url',      :s3_region      => 'eu-central-1'  validates_attachment :widesky, content_type: { content_type: "text/html" }  

In my controller I have the following:

require 'erb'    @campaign = Campaign.new(campaign_params)    erb_file = 'templates/banners/widesky.html.erb'    erb_str = File.read(erb_file)    @title = "John" #variable to be used within template  renderer = ERB.new(erb_str)  result = renderer.result()    file = File.open('index.html', 'w') do |f|    f.write(result)  end    @campaign.widesky = file  @campaign.widesky_url = @campaign.widesky.url  

Now, the problem with the above is the following: 1) the file is currently being saved locally, which I don't want (hosting on Heroku but temporarily is a good idea so I can see whether the file is being generated correctly). 2) The template does not use the variable @title, so no dynamic content is rendered. 3) Paperclip is giving me the following error: Paperclip::AdapterRegistry::NoHandlerError in Api::CampaignsController#create and No handler found for 7031

Any ideas how I could get this to work?

Rails Paperclip upload not working AWS

Posted: 25 Oct 2016 05:01 AM PDT

I'm running an Elasticbeanstalk instance with a Rails5 app running with Postgres. Everything works ok apart from when I try to upload an image via Paperclip. I keep getting the following error:

I, [2016-10-25T11:09:16.483161 #10586] INFO -- : [441264a9-b12c-4a01-befd-6d20896ba3b5] Completed 500 Internal Server Error in 96ms (ActiveRecord: 7.4ms) F, [2016-10-25T11:09:16.483975 #10586] FATAL -- : [441264a9-b12c-4a01-befd-6d20896ba3b5]
F, [2016-10-25T11:09:16.484012 #10586] FATAL -- : [441264a9-b12c-4a01-befd-6d20896ba3b5] Errno::EACCES (Permission denied @ rb_sysopen - /var/app/current/public/system/users/avatars/000/000/002/original/pic.jpg): F, [2016-10-25T11:09:16.484047 #10586] FATAL -- : [441264a9-b12c-4a01-befd-6d20896ba3b5]
F, [2016-10-25T11:09:16.484064 #10586] FATAL -- : [441264a9-b12c-4a01-befd-6d20896ba3b5] app/controllers/users_controller.rb:41:in `update'

I'm guessing it's a permissions problem with the public folder. But nervous of messing around with things I won't know how to put right...

Devise: Add User Details in different table

Posted: 25 Oct 2016 06:58 AM PDT

I have two models User and Person

I want to stick with the default table for the user offered by Devise to include only email and password and add User details in Person

Here is my models

class Person < ApplicationRecord     belongs_to :user   end  

User Model

 class User < ApplicationRecord      ...      has_one :person      ...   end  

I also override RegistrationController.rb to look like this

class RegistrationsController < Devise::RegistrationsController      def sign_up_params    params.require(:user).permit(:first_name, :email, :password, :password_confirmation)  end    end  

and here is the view

<h2>Sign up</h2>    <%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>    <%= f.error_notification %>    <%= f.fields_for :person do |p| %>    <%= p.text_field :first_name %>    <%= p.text_field :last_name %>    <% end %>      <div class="form-inputs">      <%= f.input :email, required: true, autofocus: true %>      <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %>      <%= f.input :password_confirmation, required: true %>    </div>      <div class="form-actions">      <%= f.button :submit, "Sign up" %>    </div>  <% end %>    <%= render "devise/shared/links" %>  

With the code it didn't work, and it didn't update the people column while registration

How Can I get devise to add details in two models using the only one form offered by devise ? To add email and password in Users Table and other details e.g. first_name in People Table

Updating the values on Many-to-Many relationship table

Posted: 25 Oct 2016 07:25 AM PDT

I'm facing an issue on the many to many relationship table using ruby on rails.

I have two tables and a relationship table(which is a joining table). They are named as follow

  1. User
  2. Role
  3. Role_User

My problem is how do i update the values of user roles on the 3rd table.

Example

If I assign a

user_id 34 to admin(role_id = 2)

user_id 34 to supervisor(role_id = 3)

I should have two entries on Role_User table. Now I would like to update user_id 34 to admin(role_id = 1) How do I do this on rails

I have updating the user details with update_all command on rails like below

@user = User.where(id: user_params[:id]);  @user.update_all(      first_name: user_params[:first_name],      last_name: user_params[:last_name],      email: user_params[:email],      contact_number: user_params[:contact_number],      user_name: user_params[:user_name],      password: user_params[:password]  );  

raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?

Posted: 25 Oct 2016 04:58 AM PDT

  def check_pending!(connection = Base.connection)      raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection)    end      def load_schema_if_pending!  

i have run: bin/rake db:migrate RAILS_ENV=development but still nothing happens, i was trying to add community engine to my rails 4.2 app, help anyone?

Thanks

How to temporarily disable Omniauth authentication in Rails?

Posted: 25 Oct 2016 06:47 AM PDT

I made a Facebook Devise authentication on my Rails 5 site. All the code and settings are standart.

But now I would like to temporarily disable it. I want to put a temporary redirect to user_facebook_omniauth_authorize_path back to the calling page with some flash message "The facebook authorization is temporarily blocked".

But I haven't found any controller where I could set such a redirect. Or should I search for some callback? When I click user_facebook_omniauth_authorize_path I see in console

Started GET "/users/auth/facebook" for 127.0.0.1 at 2016-10-25 14:21:39 +0300 I, [2016-10-25T14:21:39.699171 #23486] INFO -- omniauth: (facebook) Request phase initiated.

But no controller is called. How to do the redirect then?

I have the

    class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController        def facebook  .....        end      end  

controller - but it is called AFTER the www.facebook.com request - not BEFORE as I need.

Extending an ActiveRecord Polymorphic Association with JOIN statements?

Posted: 25 Oct 2016 04:36 AM PDT

My tables are set up such that Child has a 1:1 relationship with Parent.

They share a primary key (id):

  • Parent has id and type and name
  • Child has id and health

The Child is a polymorphic inheritance of the Parent. My goal is that Child.find(1) should return a Child object which responds to both name and health. The SQL statement would hypothetically look something like this:

SELECT parents.id, parents.name, childs.health FROM parents LEFT JOIN childs ON childs.id = Parents.id WHERE parents.id = 1 AND parents.type = 'Child' LIMIT 1

Thus I've attempted to use Polymorphic Inheritance in ActiveRecord:

class Parent < ApplicationRecord  class Child < Parent  

When I attempt to execute Child.find(1), I see:

SELECT `parents`.* FROM `parents` WHERE `parents`.`type` IN ('Child') AND `parents`.`ID` = 1 LIMIT 1 => #<Child id: 1, type: "Child", name: "Hello">

Notably, there's no JOIN on the child table, yet I receive a Child object back. This leads to the unexpected behavior that the Child object does not respond to health. Curiously, if I add an explicit table association to the Child class (self.table_name = "childs"), then the query pattern changes to:

> c = Child.find(1) Obtainable Load (0.3ms) SELECT `childs`.* FROM `childs` WHERE `childs`.`ID` = 2 LIMIT 1

Now I can access the health, but not the type or name.

How can I correctly create this JOIN association such that an attempt to load a Child object successfully JOINs the data from the parent?

How does Rails View Helper work

Posted: 25 Oct 2016 06:02 AM PDT

I recently came across a tricky situation related to rails view helpers. The situation is like follows-

I am having a controller as Feature1::Feature1.1::Feature1.1.1Controller. The Feature1.1 also includes other controllers like Feature1.1.2Controller, Feature1.1.3Controller...

So ofcourse related view helpers in folder app/helpers/feature1/feature1.1/...

Now the real problem I am facing is that a few helpers for feature1.1 includes the same method name method1 with related definition.

I was wondering how rails identifies all these helpers as I am noticing that the method1 i.e. being called in a view for the controller feature1.1.1 is using the definition of the method1 i.e. written for the controller feature1.1.2.

So does rails consider all helper modules defined in one folder as one?

In a view feature1/feature1.1/feature1.1.1/index I am making a method call for method1.

I am using rails3

How to stop rspec from dropping the test database before tests

Posted: 25 Oct 2016 06:49 AM PDT

I have two Rails apps that use the same database. One app is managing the database through migrations but the other is just accessing it.

For some reason when I run tests with RSpec in the app that is not managing the database it drops the database before running the tests. But because this app does not know how to recreate the database all tests will fail.

How can I tell RSpec not to drop the database, just use it as it is?

Rails 5: Table name not being inferred through class_name

Posted: 25 Oct 2016 04:06 AM PDT

I have the following rails model:

class Connection < ApplicationRecord    belongs_to :graph    has_one :node, class_name: 'Person'  end  

Each connection.node points to a Person.

I'd like to be able to find connections which point to particular people.

For example:

Connection.joins(:nodes).where(node: {first_name: 'Jane'} )

However this gives me the error:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "node"  LINE 1: SELECT "connections".* FROM "connections" WHERE "node"."firs...                                                          ^  : SELECT "connections".* FROM "connections" WHERE "node"."first_name" = $1  

I believe this is because its querying nodes instead of people as it needs to.

I've also tried joins(:people) but that gives an error of no association named people being found.

Any ideas how to achieve this, without having to rename the association?

Can we create Ruby on Rails API-only Application with ActionCable Live updates?

Posted: 25 Oct 2016 06:22 AM PDT

How-to create RoR API-only application with ActionCable live updates?

Firstly I don't have any experience in Building API's and Front End Technologies, recently I started API's build.

I've checked lot of documents, and no use.

Kindly, Help me with some good resources or stuff which includes - how we need to subscribe, publish and broadcast using ActionCable in API-only application.

Nginx + Phusion Passenger + Rails = staging ENV won't be set

Posted: 25 Oct 2016 03:51 AM PDT

I am having trouble making phusion passenger see that the server is set for staging instead of production.

I have changed /etc/nginx/sites-enabled/<my app>

using sudo nano /etc/nginx/sites-enabled/<my app>

server {      listen 80;      server_name <app name>;      return 301 https://$host$request_uri;  }  server {    listen 443 ssl;    server_name <app name>;      passenger_enabled on;    passenger_app_env staging;    rails_env staging;    root /home/deploy/apps/<app name>/current/public;      location ~ /.well-known {      allow all;    }  }  

basically added/changed lines

passenger_app_env staging; rails_env staging;

but still not working, is there anything else i need to do?

Rails sending a dynamic content and layout to action mailer

Posted: 25 Oct 2016 03:31 AM PDT

I am creating a dynamic mailer where we can set content as well as css style also. like we create database including subject and mail_body. and the mail body contain the html code including inline css. now how can i pass it to action mailer and fire a mail.

Thanks in advance.

how to submit rails form once with validation check if only all fields are valid

Posted: 25 Oct 2016 07:41 AM PDT

I have a form in my rails app but it submits multiple times when we click multiple times i want to submit the form once with checking all validations, I tried disabling the button on click but its only desables button with click, not actually send data nor checking validations. please help me, Thanks in advance.

Questions about Fat-Model, Skinny-Controller practice

Posted: 25 Oct 2016 05:41 AM PDT

How do you decide that a line of code must be moved from controller to model?

I've done some research already about this best practice and here's the best explanations so far, but I hope you guys can expand this well because my newbie brain can't fully comprehend it :)

  1. any non-response-related logic should go in the model
  2. you only need process request parameters and initialize model layer in controllers
  3. Business logic need to be implemented in model layer

EDIT: Let's say I want to refactor my controller below from:

class TaskController < ApplicationController    def index      @tasks = Task.find_all_by_complete(:false, :order => "created_at DESC")    end  end  

to

class TaskController < ApplicationController    def index      @tasks = Task.find_incomplete    end  end  

Which of these 2 code blocks are correct?

class Task < ActiveRecord::Base    def self.find_incomplete      find_all_by_complete(:false, :order => "created_at DESC")    end  end  

or

class Task < ActiveRecord::Base    def find_incomplete      self.find_all_by_complete(:false, :order => "created_at DESC")    end  end  

EDIT2: If I want to refactor my controller below from:

@average_review = @surf_school.surf_school_reviews.average(:rating).round(2)  

to

@average_review = @surf_school.average_review  

my code inside model should be:

def average_review    self.surf_school_reviews.average(:rating).round(2)  end  

No comments:

Post a Comment