Monday, March 14, 2016

Add filter to Middleman "previous article" loop | Fixed issues

Add filter to Middleman "previous article" loop | Fixed issues


Add filter to Middleman "previous article" loop

Posted: 14 Mar 2016 06:51 AM PDT

I'm pretty new to this, so I hope I get this right.

I'm building a portfolio site with Middleman. I've activated the blog extension and I use articles as case studies. The articles contain "featured" in their front matter, which I either set to "true" or "false".

The "featured: true" articles are displayed on the homepage. At the bottom of these articles I've added the following code to be able to navigate to the previous and next articles:

<% prev_article = current_article.previous_article %>  <% if prev_article %>    <a href="<%= prev_article.url %>"><%= prev_article.title %></a>  <% end %>  

Thing is, I would like to add a filter so that just the articles with "featured: true" are added to this loop.

I've tried the following:

<% prev_article = current_article.previous_article %>  <% if prev_article && prev_article.data.featured == "true" %>    <a href="<%= prev_article.url %>"><%= prev_article.title %></a>  <% end %>  

But, as expected, this outputs nothing because both conditions aren't met. Hope anyone can help me out :)

Searh issue in Ruby-on-Rails

Posted: 14 Mar 2016 06:54 AM PDT

I currently have a DB in Ruby on Rails, however, I have been having trouble with the documentation on how to do much other than list all of the items in DB. I am still new to the this language as a whole, and wish I didn't need to ask for so much help, but here it goes. My pertinent code is as follows:

migrate/(DB name)

class CreateArticles < ActiveRecord::Migration    def change      create_table :articles do |t|        t.string :title        t.text :text          t.timestamps null: false      end    end  end  

articles_controller.rb

class ArticlesController < ApplicationController    def index      @articles = Article.all        Article.search(params[:id])    end      def show      @article = Article.find(params[:search])    end      def new      @article = Article.new    end      def edit      @article = Article.find(params[:id])    end      def create      @article = Article.new(params.require(:article).permit(:title, :text))        if @article.save        redirect_to @article      else        render 'new'      end    end      def update      @article = Article.find(params[:id])        if @article.update(article_params)        redirect_to @article      else        render 'edit'      end    end      def destroy      @article = Article.find(params[:id])      @article.destroy        redirect_to articles_path    end      private      def article_params        params.require(:article).permit(:title, :text)      end  end  

article.rb

class Article < ActiveRecord::Base      validates :title, presence: true,                      length: { minimum: 5 }        def self.search(search)      if search          @article = Article.where('name LIKE ?', "%#{search}%")      else          @article = Article.all      end      end    end  

index.html.rb

<h1>Listing articles</h1>    <%= link_to 'New article', new_article_path %>     <table>    <tr>      <th>Title</th>      <th>Text</th>      <th colspan="3"></th>    </tr>      <% @articles.each do |article| %>      <tr>        <td><%= article.title %></td>        <td><%= article.text %></td>        <td><%= link_to 'Show', article_path(article) %></td>        <td><%= link_to 'Edit', edit_article_path(article) %></td>        <td><%= link_to 'Destroy', article_path(article),                method: :delete,                data: { confirm: 'Are you sure?' } %></td>      </tr>    <% end %>        <%= form_tag articles_path, :method => 'get' do %>       <p>          <%= text_field_tag :search, params[:search] %>          <%= submit_tag "Search", :name => nil %>       </p>   <% end %>    </table>  

Thanks for any help in advance!

Test that a toast fires off in a Capybara feature spec?

Posted: 14 Mar 2016 06:46 AM PDT

I have a Rails app that I've recently refactored standard flash[:success] messages to use a flash[:toast], using http://materializecss.com/dialogs.html

Here's what I'm doing with my flash partial:

<% flash.each do |type, message| %>    <% if type == "success" %>      <div class="alert alert-success alert-dismissable" role="alert">        ...      </div>    <% elsif type == "toast" %>      <script>        $(function() {          Materialize.toast('<%= message %>', 3000);        });      </script>    <% else %>      <div class="alert alert-danger alert-dismissible" role="alert">        ...      </div>    <% end %>  <% end %>  

This works and looks awesome, especially on mobile and for complex data pages where I'm sending the user back to the middle of the page, and a standard flash success message on the top of the page would not be visible.

I can easily test if flash[:toast] is not nil in a controller test, but in capybara feature tests, I don't have access to that, and I can't use the standard code that I used to use to test flash[:success] like:

expect(page).to have_content("Your email address has been updated successfully.")  expect(page).to have_css(".alert-success")  

Right now I am resorting to just testing that an alert danger is not present, like:

expect(page).to_not have_css(".alert-danger")  

This works, but isn't really testing that the toast fired off. Is there any way to check that the javascript fired or that the toast appeared on the page for the 3 seconds?

How to have a main object in my ruby on rails json data

Posted: 14 Mar 2016 06:44 AM PDT

Question, I am loading data from my db to my local redis server I want this data to have a main object like "animals" for some reason it always save it with out a main object. Any help would be greatly appreciated.

Here is my json data

[      {          "what_animal": "Lion",          "create_date": "March-14-16",      },      {          "what_animal": "Zebra",          "create_date": "March-15-16",      },      {          "what_animal": "Monkey",          "create_date": "March-16-16",      }  ]  

Here is what I would like it to look like

{    "animals": [      {          "what_animal": "Lion",          "create_date": "March-14-16",      },      {          "what_animal": "Zebra",          "create_date": "March-15-16",      },      {          "what_animal": "Monkey",          "create_date": "March-16-16",      }   ]  }  

Here is my method to get and update my redis server with the data in my db

def self.fetch_animals    animals = $redis.get("all_animals")    if animals.nil?      animals = Animals.all.order('create_date ASC').to_json      $redis.set("all_animals", animals)      $redis.expire("all_animals", 1.hour.to_i)    end    animals = JSON.load animals  end  

Testing a button which rendered ajax in ruby on rails

Posted: 14 Mar 2016 06:39 AM PDT

the problem is I am trying to write test for a button which rendered ajax in views,but it always shows cannot find the button or link(which means neither click_button nor click_link works),or say the format is wrong. What shall I change in my code to make the test pass? Thank you for your help. My test code is show below:

describe 'Activate user'do  specify 'Admin logged in', :js => true  do    admin = FactoryGirl.create(:admin)    user = User.create(first_name: 'John', last_name: 'Smith', company: 'Genesys', position: 'Manager',role: 'member', access_token: '', email: 'user1@example.co.uk', password: 'password', password_confirmation: 'password', active: false)    login_as admin    visit '/'    visit "/controlpanel"    click_link("user-freeze-btn-#{user.id}")    expect(user.active).to eq(true)  end  end  

and this is the code in the view which is a button rendering ajax:

= render :partial => 'user_freeze_btn', :locals => {:text => (user.active ? 'Activated' : 'Frozen'), :user => user, :btn_class => (user.active ? 'btn-success' : 'btn-danger')}  

Here are the ajax "_user_freeze_btn.html.haml":

%td= link_to text, {:remote => true, :controller => :users, :action => :toggle, :id => user}, {:class => "btn #{btn_class} btn-sm user-freeze-btn", :id => "user-toggle-btn-#{user.id}"}  

and "_user_freeze_btn.jason.haml":

%td= link_to text, {:remote => true, :controller => :users, :action => :toggle, :id => user}, {:class => "btn #{btn_class} btn-sm user-freeze-btn", :id => "user-toggle-btn-#{user.id}"}  

Vote implementation for posts in Rails 4

Posted: 14 Mar 2016 06:47 AM PDT

I have models User, Post, Vote. Here is my vote model:

class Vote < ActiveRecord::Base    SCORE_REGEX = /-1|1/    # Relations    belongs_to :user    belongs_to :post    # Validations    validates :score,      allow_nil: true,      format: {with: SCORE_REGEX }  end  

My posts appear on homepage and user profile. My controllers are: static_pages_controller (this is the controller holds home page), users_controller, posts_controller, votes_controller. I have template for post in views/posts/_post.html.erb which looks like this:

 <%= link_to post.id, post %> <br>   <%= link_to post.user.name, post.user %>       <%= post.content %>    posted <%= time_ago_in_words(post.created_at) %> ago. <br>    <% if post.edited %>      post has been edited <%= time_ago_in_words(post.updated_at) %> ago.    <% end %>    <% if current_user?(post.user) %>      <%= link_to "delete", post, method: :delete %>,      <%= link_to "edit", edit_post_path(post)%>    <% end %>    <%= render 'shared/vote_form' %>  

How do I make a working vote buttons (Like, unlike, dislike, undislike) for these posts?

deploying application locally through apache2 or Nginx

Posted: 14 Mar 2016 06:35 AM PDT

i have been developing a project for my college & now i want to deploy it in production so that other users can use it & concurrent request can be handled efficiently. i have been facing problem using apache2 after specifying the path of rails folder it is not executing rails application so can anyone can help me in providing the perfect way or instructions to deploy my rails application on apache2 or Nginx.

Not Sending Mail from Local Ubuntu 14.04

Posted: 14 Mar 2016 06:35 AM PDT

I am using ubuntu 14.04.I have setup SMTP server using below command

   1. sudo apt-get install mailutils     2. sudo nano /etc/postfix/main.cf           readme_directory = no           smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination           myhostname = qi34 <Local Machine Name>           alias_maps = hash:/etc/aliases           alias_database = hash:/etc/aliases           mydestination = tracksynq, qi34, localhost.localdomain,   localhost, gmail, quantuminventions           relayhost =           mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128           mailbox_size_limit = 0           recipient_delimiter = +           inet_interfaces = loopback-only           inet_protocols = all           myorigin = /etc/mailname       3. sudo apt-get install postfix       4. sudo dpkg-reconfigure postfix       5. sudo service postfix restart       6. sudo apt-get install mutt     

when I am sending mail, It doesn't send any mail.Another thing I am getting " Undelivered Mail Returned to Sender" the message.

How to open and close streaming from rather channels?

Posted: 14 Mar 2016 06:16 AM PDT

I installed rails 5 and start to create app with ActionCable. There are to much examples how to create "Dialog" app, but I don't found, how to work with 2(or more) channels, I mean, if I need 1 type of channel on the main page and 2nd type on the another pages, how to do that if user come to the main page - 1st channel is start streaming, when he come to another page - 1st is closing and opened 2nd type of?

Thanks for any help!

Ruby on Rails and Twilio

Posted: 14 Mar 2016 06:19 AM PDT

After following instruction on how to integrate Twilio in ROR apps, I have an issues when making a curl request:

curl -X POST http://localhost:3000/twilio/voice -d 'foo=bar'  

Return me:

<html><body>You are being <a href="http://localhost:3000/users/sign_in">redirected</a>.</body></html>  

Thanks!!

Difference between assert and assert_select

Posted: 14 Mar 2016 06:24 AM PDT

I am writing a test case in rails Minitest, I have two scenarios, first one is :

 assert_select "button.btn[type=submit]", I18n.t('pay_and_post_job')    

But when i run this then i get an error

Expected at least 1 element matching "button.btn[type=submit]", found 0.. Expected 0 to be >= 1.

But if i write the same assertion as :

 assert "button.btn[type=submit] #{I18n.t('pay_and_post_job')}"  

Then test is passing

Can someone explain this to me what exactly is happening??

Rails4: ActionController::ParameterMissing (param is missing or the value is empty:)

Posted: 14 Mar 2016 06:27 AM PDT

I studied the rails tutorial by Michael Hartl and I'd like to add new service to this app.

Although I created new model, controller and views, the following error appeared when I submit f.submit "Create my schedule" in _schedule_form.html.erb.

This error may be caused by strong parameter, I guess.

It would be appreciated if you could give me any suggestion.

development.log

ActionController::ParameterMissing (param is missing or the value is empty: schedule):    app/controllers/schedules_controller.rb:30:in `schedule_params'    app/controllers/schedules_controller.rb:9:in `create'  

schedule_controller.rb

class SchedulesController < ApplicationController    before_action :logged_in_user, only: [:create, :destroy]      def new      @schedule = Schedule.new    end      def create      @schedule = current_user.schedules.build(schedule_params)      if @schedule.save        flash[:success] = "schedule created!"        redirect_to root_url      else        render 'new'      end    end    ...      private        def schedule_params        params.require(:schedule).permit(:title)      end    end  

views\schedules\new.html.erb

<div class="row">    <div class="col-md-12">      <p>Create schedule (<%= current_user.name %>)</p>      <%= render "schedule_form" %>    </div>  </div>  

views\schedules\ _schedule_form.html.erb

<%= form_for(@schedule) do |f| %>    <%= render 'shared/error_messages', object: f.object %>    <div class="input-group">      <span class="input-group-addon">Title</span>      <input type="text" class="form-control">    </div>    <br>    <%= f.submit "Create my schedule", class: "btn btn-primary" %>    <br>  <% end %>  

speed up a 2-3hour rake task

Posted: 14 Mar 2016 06:41 AM PDT

I've got this rake task on rails that populates my database, It needs to run daily.

require 'open-uri'  require 'csv'  namespace :tm do    task reload: :environment do      gzipped = open('csv link')      csv_text = Zlib::GzipReader.new(gzipped).read      csv = CSV.parse(csv_text, headers: true)        csv.each do |row|        if row[4] == 'logo url'        else        tmdate = Date.parse(row[10]).strftime('%Y-%m-%d')        viatmdate = Date.parse(row[10]).strftime('%d/%m/%Y')        swtmdate = row[10]        tmlocation = row[6].split('at ')[1]        place = row[11].split('|')[1]        place1 = row[11].split('|')[2]        place2 = row[11].split('|')[3]        location = '' + place + ', ' + place1 + ', ' + place2 + ''        tmtime = row[9]        text = row[7].gsub('text', '')        if text.include? '&#xFFFD;&#xFFFD'          eventname = text.gsub('&#xFFFD;&#xFFFD', 'e')        else          eventname = text.gsub(/[ªÀÈÌÒÙàèìòùÁÉÍÓÚáéíóúÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜŸäëïöüÿ]/, '')        end          if text.include? '&#xFFFD;&#xFFFD'          tmname = text.gsub('&#xFFFD;&#xFFFD', 'e')        else          tmname = text.gsub(/[ªÀÈÌÒÙàèìòùÁÉÍÓÚáéíóúÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜŸäëïöüÿ]/, '')      end      if text.include? ' -'        tmnamesplit = text.split(' -')[0]      end      if tmname[/[^0-9]/].present?        tmnamenn = tmname.gsub(/[^0-9]/i, '')      end          text2urldb = text2.where('eventtitle ILIKE ? AND eventdoortime = ? ', "%#{tmname.gsub(/[\-\:\ ]/, '%')}%", tmdate.to_s).first          text3urldb = text3.where('product_name ILIKE ? AND delivery_time = ? AND valid_from = ?', "%#{tmname}%", tmtime.to_s, tmdate.to_s).first            text1urldb = text1.where('product_name ILIKE ? AND specifications = ? AND promotional_text = ?', "%#{tmname}%", viatmdate.to_s, "%#{place}%").first            if tmnamesplit.present?            if text1urldb.blank?              text1urldb = text1.where('product_name ILIKE ? AND specifications = ?', "%#{tmnamesplit}%", viatmdate.to_s).first            end            if text3urldb.blank?              text3urldb = text3.where('product_name ILIKE ? AND delivery_time = ? AND valid_from = ?', "%#{tmnamesplit}%", tmtime.to_s, tmdate.to_s).first            end          end            if text1urldb.blank?            text1urldb = text1.where('product_name ILIKE ? AND specifications = ? AND promotional_text = ?', "%#{tmname}%", viatmdate.to_s, "%#{location}%").first            if text1urldb.blank?              text1urldb = text1.where('product_name ILIKE ? AND specifications = ?', "%#{tmname}%", viatmdate.to_s).first            end            if text1urldb.blank?              text1urldb = text1.where('product_name ILIKE ? AND specifications = ? AND promotional_text = ?', "%#{tmname}%", viatmdate.to_s, "%#{tmlocation}%").first            end          end              if text1urldb.present?          vurl = text1urldb.merchant_deep_link          txt = vurl          re1 = '.*?' # Non-greedy match on filler          re2 = '(?:[a-z][a-z]+)' # Uninteresting: word          re3 = '.*?' # Non-greedy match on filler          re4 = '(?:[a-z][a-z]+)' # Uninteresting: word          re5 = '.*?' # Non-greedy match on filler          re6 = '(?:[a-z][a-z]+)' # Uninteresting: word          re7 = '.*?' # Non-greedy match on filler          re8 = '(?:[a-z][a-z]+)' # Uninteresting: word          re9 = '.*?' # Non-greedy match on filler          re10 = '(?:[a-z][a-z]+)'    # Uninteresting: word          re11 = '.*?'    # Non-greedy match on filler          re12 = '((?:[a-z][a-z]+))'  # Word 1          re = (re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8 + re9 + re10 + re11 + re12)          m = Regexp.new(re, Regexp::IGNORECASE)          if m.match(txt)            word1 = m.match(txt)[1]          end        end            gmiurl = text3urldb.merchant_deep_link if text3urldb.present?          gigurl = text2urldb.eventurl if text2urldb.present?          api = HTTParty.get(URI.encode('text url' + tmname + '&when_from=' + swtmdate)).parsed_response        api1 = api['Paging']        api2 = api1['TotalResultCount']          if api1.blank?          newapi = HTTParty.get(URI.encode('texturl' + tmnamenn + '&when_from=' + swtmdate)).parsed_response          paging = newapi['Paging']          api2 = paging['TotalResultCount']          if newapi.blank?            apisplit = HTTParty.get(URI.encode('texturl' + tmnamesplit + '&when_from=' + swtmdate)).parsed_response            pagingsplit = apisplit['Paging']            api2 = pagingsplit['TotalResultCount']          end        end        text1 = vurl        text3 = gmiurl        text2 = gigurl          if api2 == 0        else          swurl = api['Events'].first['SwURL']        end        event = Event.find_by(time: row[9], date: row[10], eventname: eventname, eventvenuename: location)          if event.present?          event.update(event_type: word1, text: row[8], eventimage: row[4], textlink: swurl, text1link: text1, text3url: text3, text2url: text2)        else          Event.create(time: row[9], date: row[10], event_type: word1, text: row[8], eventimage: row[4], eventname: eventname, eventvenuename: location, textlink: swurl, text1link: text1, text3url: text3, text2url: text2)        end        end      end    end  end  

Now I'm willing to do anything, The csv link is an api link to a csv. I'm willing to split this up over multiple files, The issues it i have no idea how long it takes to run, So it'd have to be a once complete run next rake task.

At the moment, This takes around 2-3 hours to complete and populate the db.

Any ideas how to speed this up?

Thanks

Sam

Schema.rb issue (changes in 2 branches)

Posted: 14 Mar 2016 05:58 AM PDT

Let's say I'm working on a branch 'master'. It's clean. I made another branch 'task' and added a new table to database. I commited the changes but didn't push to remote repo.

Then I switched to the 'master' branch and make changes to db also. When I press git diff db/schema.rb I can see that the table was added to my schema, but I didn't add it in my 'master' branch which means I can see differences in schema.rb file but the migration itself is in a 'task' branch.

How do I commit and push the changes from 'master' branch?

Ruby parse DateTime with variable

Posted: 14 Mar 2016 06:23 AM PDT

I'm trying to parse a specific hour of a specific date. When I put the date directly as an argument, it works fine, but when I create a variable and put it in the argument it returns the current date.

Why is that?

NOTE: the variable time is 9pm and I need to parse 9pm of 12 March 2016.

datetime = DateTime.new(2016,3,12,9)  => Sat, 12 Mar 2016 09:00:00 +0000    DateTime.parse("sat 12 march 2016 9pm")  => Sat, 12 Mar 2016 21:00:00 +0000    DateTime.parse("datetime 9pm")  => Mon, 14 Mar 2016 21:00:00 +0000  

Single spec duration

Posted: 14 Mar 2016 06:47 AM PDT

Is there a way in RSpec to show every single test duration and not just the total suite duration?

Now we have

Finished in 7 minutes 31 seconds (files took 4.71 seconds to load)

but I'd like to have something like

User accesses home and   he can sign up (finished in 1.30 seconds)   he can visit profile (finished in 3 seconds)   .   .   .  Finished in 7 minutes 31 seconds (files took 4.71 seconds to load)  

Routing for multiple profile views

Posted: 14 Mar 2016 06:50 AM PDT

I no have idea how to implement display of the multiple user's profile. I use STI inheritance to for few types of person.

What I want?

I want to create the simplest routing for each type of person, and possibility to display and edit profile for each type of person. Now I have this: enter image description here

I thought about profile view(backend_people_profile) only for people model, and update_profile for each type. Is it correct? Now I have too many repetitive paths.

routes.rb

namespace :backend do        resources :managers, except: [:new, :create] do          get '/profile', to: 'people#show_profile'        end          resources :clients, except: [:new, :create] do          get '/profile', to: 'people#show_profile'        end          resources :receptionists, except: [:new, :create] do          get '/profile', to: 'people#show_profile'      end          resources :trainers, except: [:new, :create] do          get '/profile', to: 'people#show_profile'        end          resources :lifeguards, except: [:new, :create] do          get '/profile', to: 'people#show_profile'        end    end  

Rails: validate date range uniqueness at database level

Posted: 14 Mar 2016 06:04 AM PDT

I have a Rails app with these 3 models - RentingUnit, Tenant & Booking.

A Tenant can Book a RentingUnit by filling up a form for a new booking with these fields - renting_unit_id, tenant_id, start_date, end_date.

start_date & end_date together form the duration the renting_unit is booked for.

With that, I want to make sure that a renting_unit can not be booked for a duration that overlaps with any duration it's already booked for. (I'm using PostgreSQL database if that matters.)

I came across related answers with Model level validations but I want to enforce uniqueness at the database level too, to account for a possible race condition.

How can I go about implementing it?

Rails PSQL query JSON for nested array and objects

Posted: 14 Mar 2016 05:15 AM PDT

So I have a json (in text field) and I'm using postgresql and I need to query the field but it's nested a bit deep. Here's the format:

[    {      "name":"First Things",      "items":[        {          "name":"Foo Bar Item 1",          "price":"10.00"        },        {          "name":"Foo Item 2",          "price":"20.00"        }      ]    },    {      "name":"Second Things",      "items": [        {          "name":"Bar Item 3",          "price":"15.00"        }      ]    }  ]  

And I need to query the name INSIDE the items node. I have tried some queries but to no avail, like: .where('this_json::JSON @> [{"items": [{"name": ?}]}]', "%#{name}%"). How should I go about here?

I can query normal JSON format like this_json::JSON -> 'key' = ? but need help with this bit.

Rails 4 - .js.erb rendered into layout, not executed (driving me nuts!)

Posted: 14 Mar 2016 05:40 AM PDT

I'm attempting to update a span using a simple link_to and an action. Visually when I click the link 'nothing happens', (the page doesn't change).

Looking at the response to the request, I see my layout with the contents of the js.erb file inserted where the layout yields.

My environment is Rails 4.2 running under Docker on OS X and also Elastic Beanstalk on AWS.

app/views/admin/games.haml:  %p=link_to("Hint please", {:action=> "hint"}, :remote => true)    %span#hint    where next?  

app/controllers/admin_controller.rb:

  def hint      respond_to do |format|        format.js      end    end  

app/views/admin/hint.js.erb:

$("#hint").text('hello coffee');  

rails log on clicking the link:

Started GET "/admin/hint" for 192.168.99.1 at 2016-03-14 12:04:33 +0000  Cannot render console from 192.168.99.1! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255  Processing by AdminController#hint as JS      Rendered admin/hint.js.erb within layouts/admin (0.0ms)      Rendered application/_favicon.haml (8.9ms)  Completed 200 OK in 197ms (Views: 196.0ms | ActiveRecord: 0.0ms)  

I followed the debug instructions at https://www.alfajango.com/blog/rails-js-erb-remote-response-not-executing/ - I see no Javascript errors. The response is the layout with the contents of the .js.erb rendered as text where the yield command is in the layout:

<div id='main'>      <div class='header'>          <h1></h1>          <h2></h2>      </div>      <div class='content'>          $("#hint").text('hello coffee');      </div>  </div>  

This is driving me crazy, thank you for your help.

Error in searching for :all

Posted: 14 Mar 2016 06:53 AM PDT

I am currently trying to create a search method, I have a database all setup, however, I am running into the errors

ActiveRecord::RecordNotFound in ArticlesController#index

and

Couldn't find Article with 'id'=all

Here is the pertinent code:

Articles_controller.rb

class ArticlesController < ApplicationController    def index      @articles = Article.all        @articles = Article.search(params[:id])    end      def show      @article = Article.find(params[:search])    end      def new      @article = Article.new    end      def edit      @article = Article.find(params[:id])    end      def create      @article = Article.new(params.require(:article).permit(:title, :text))        if @article.save        redirect_to @article      else        render 'new'      end    end      def update      @article = Article.find(params[:id])        if @article.update(article_params)        redirect_to @article      else        render 'edit'      end    end      def destroy      @article = Article.find(params[:id])      @article.destroy        redirect_to articles_path    end      private      def article_params        params.require(:article).permit(:title, :text)      end  end  

article.rb

class Article < ActiveRecord::Base      validates :title, presence: true,                      length: { minimum: 5 }        def self.search(search)      if search          @article = Article.find(:all, :conditions => ['name LIKE ?', "%#{search}%"])      else          @article = Article.find(:all)      end      end    end  

index.rb

<h1>Listing articles</h1>    <%= link_to 'New article', new_article_path %>     <table>    <tr>      <th>Title</th>      <th>Text</th>      <th colspan="3"></th>    </tr>      <% @articles.each do |article| %>      <tr>        <td><%= article.title %></td>        <td><%= article.text %></td>        <td><%= link_to 'Show', article_path(article) %></td>        <td><%= link_to 'Edit', edit_article_path(article) %></td>        <td><%= link_to 'Destroy', article_path(article),                method: :delete,                data: { confirm: 'Are you sure?' } %></td>      </tr>    <% end %>        <%= form_tag articles_path, :method => 'get' do %>       <p>          <%= text_field_tag :search, params[:search] %>          <%= submit_tag "Search", :name => nil %>       </p>   <% end %>    </table>  

Sorry for all the code to look through. The errors I am getting are from running localhost:3000/articles, where I receive these error messages from the server. I should note that I am still very new to both Ruby and Ruby on Rails, however, I aim to learn and find seeing proper code to help me quite significantly (I am dyslexic and tend to be a visual learner).

I truly appreciate your help in advance.

How to Combine Rails and Html together to make a form with function

Posted: 14 Mar 2016 04:38 AM PDT

Here is my rails form, but it is just a text field or text area function, I may wanna it to be selected, and I do not understand how to combine html and rails together. Here is the code of rails and html.

Case1 for text field, when I combine html and rails together, it did not work

<%=label_tag "Type date (dd-mm-yyyy)" %><br>  <%= f.text_field :date, :class => "form-control", :placeholder => "Example: 30-07-1995" %>  

Case2 for select box, How can i combine rails and html together?

      <%= f.label :selectDay %><br>        <%= f.text_field :name %>        <select day="name">          <option>Monday</option>          <option>Tuesday</option>          <option>Wednesday</option>          <option>Thursday</option>          <option>Friday</option>          <option>Saturday</option>          <option>Sunday</option>        </select>  

The point is when i add html code into rails form code, it did not work? Anyone help me through this, Thanks guys!!

Give each partial its own id Cocoon gem rails

Posted: 14 Mar 2016 04:16 AM PDT

I am working on an app in Rails that will allow Questions to be added to a Quiz through Link. (a has_many: through association). So far I am implementing this with the Cocoon gem.

The _form.html.erb where Questions are inserted is shown below:

<table class = "table">      <thead>          <tr>              <th>Category</th>              <th>Question</th>              <th>Answers</th>              <th></th>          </tr>      </thead>      <tbody id = "question_table">      </tbody>  </table>    <div id="questions">  <div id="questionno"></div>        <%= f.fields_for :links do |link| %>      <% render 'link_fields', f: link %>      <% end %>   </div>      <div class="links">      <div id="button_text">          <button type="button" class="btn btn-primary">              <%= link_to_add_association f, :links, :"data-association-insertion-node" => "tbody#question_table", :"data-association-insertion-method" => "append", :class => "button" do %>Add question<% end %>          </button>      </div>  </div>  

Each time link_to_add_association is called my _link_fields.html.erb is drawn. This partial contains several fields. A snippet of this file is shown below:

<tr class = "table_row" >    <div class="nested-fields link-fields" >  <div id="question_from_list">            <td class="col-sm-1">             <div class = "field">                <%= f.select :question_category, options_for_select(Category.all.collect { |category|              [category.categoryBody.titleize, category.id] }, 1), {}, { id: "categories_select_1" } %>          </div>      </td>  

What I would like to do is give each f.select its' own id. I have done some googling and it seems the way to achieve this in cocoon is with callbacks.

I am trying to use the before_insert callback to generate an id and fetch the f.select element and change its id. However this doesn't seem to be working. My code is as follows:

assets/javascripts/quizzes.coffee:

$('#questions a.add_fields').data('association-insertion-position', 'before').data 'association-insertion-node', 'this'  $('#questions').on 'cocoon:after-insert', ->    $(this).children('#categories_select_1').attr 'id', 'newId'    return  

This callback doesn't seem to do anything. Other code in my quizzes.coffee file runs absolutely fine so I am sure the file is loaded.

I am sure there is something simple I have overlooked but I am not sure where I have gone wrong.

Any help would be enormously appreciated. Thanks

My rails server cannot run on Cloud9

Posted: 14 Mar 2016 04:16 AM PDT

No matter what I try to do it won't work. Here is my current console code. All I know is that it has something to do with sass-rails. I really am looking out for some help here. I understand the GEM cannot be found however, how do I make it so it can be loaded.

/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'sass-rails'. (Bundler::GemRequireError)          from /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'          from /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each'          from /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require'          from /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each'          from /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require'          from /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.11.2/lib/bundler.rb:99:in `require'          from /home/ubuntu/workspace/config/application.rb:7:in `<top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:78:in `require'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:78:in `block in server'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `tap'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `server'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'          from /home/ubuntu/workspace/bin/rails:9:in `require'          from /home/ubuntu/workspace/bin/rails:9:in `<top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/client/rails.rb:28:in `load'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/client/rails.rb:28:in `call'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/client/command.rb:7:in `call'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/client.rb:28:in `run'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.6.4/bin/spring:49:in `<top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/binstub.rb:11:in `load'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.6.4/lib/spring/binstub.rb:11:in `<top (required)>'          from /home/ubuntu/workspace/bin/spring:13:in `require'          from /home/ubuntu/workspace/bin/spring:13:in `<top (required)>'          from bin/rails:3:in `load'          from bin/rails:3:in `<main>        And my GEM file    source 'https://rubygems.org'      # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.6'  # Use sqlite3 as the database for Active Record    gem 'sqlite3', group: [:development, :test]     # Use postgresql as the database for production   group :production do     gem 'pg'     gem 'rails_12factor'  end    gem 'sass-rails', '5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '4.1.0'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks  gem 'turbolinks'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '2.0'  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', '0.4.0', group: :doc    # Use ActiveModel has_secure_password  # gem 'bcrypt', '3.1.7'    # Use Unicorn as the app server  # gem 'unicorn'    # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development    group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug'  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> in views    gem 'web-console', '~> 2.0'      # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'  end  

Or condition is not working with rails 4

Posted: 14 Mar 2016 04:27 AM PDT

Hello I have included given code

eventCode ='AUTHORISATION'   success ='true'   paymentMethod = 'unionpay'  eventCode == 'AUTHORISATION' && success == 'true' && paymentMethod == ('alipay' || 'unionpay') #returns false  

above condition returns false but it has to return true why my condition is not working. Please help me in solving this.

Rails reverse geocoder is returning nill result

Posted: 14 Mar 2016 03:56 AM PDT

in model Location

reverse_geocoded_by :lat, :lng  after_validation :reverse_geocode    

in controller

@location = @employee.locations.find(params[:id])  @add = @location.address  

it gives me "Reserved" as a result. also i have address column in my location table to...can you tell me right way of getting address from coordinates

ALTER TABLE lhm migration deletes existing values

Posted: 14 Mar 2016 03:40 AM PDT

require 'lhm'    class RenameField1ToField2ForTable < ActiveRecord::Migration    def up      Lhm.change_table :table do |m|        m.ddl("ALTER TABLE TABLENAME CHANGE COLUMN field1 field2 FLOAT DEFAULT NULL")      end    end      def down      Lhm.change_table :table do |m|        m.ddl("ALTER TABLE TABLENAME CHANGE COLUMN field1 field2 FLOAT DEFAULT NULL")      end    end  end  

What happend:

  1. Rails-4.0: rake db:migrate
  2. Field was renamed successfully.
  3. All existing field values are erased, why? Any ideas?

//

  • old datatype was float(11)

Authentication with an Existing External API

Posted: 14 Mar 2016 06:22 AM PDT

I am building a Ruby on Rails (Rails - v4.2.3 & Ruby 2.2.2) App which consumes an existing REST API. The aforementioned API is written in PHP. I need help regarding how to manage the authentication?

On searching through various forums I came across these two gems

  1. https://github.com/lynndylanhurley/devise_token_auth
  2. https://github.com/gonzalo-bulnes/simple_token_authentication

The problem I am facing with both is that they require my app to have a users model configured (using Devise).

However My app is primarily a front end for the Existing REST API, so if I do configure my own User model, I will end up with two Data Stores (One for the APP I make and the other for the existing API).

I wish to consume the external API and not have any native models for my APP.

I believe I can use ActiveResource for this (I need more reputation points to post a link to the gem, sorry I cannot do that right now, I am new to StackOverflow):

However I am not sure how to go about managing the security of the application. More specifically what measures can I take to prevent the authentication information from being viewed in plaintext while it is being transmitted to my API server for authentication?

Thank You.

ActiveRecord find where many dates don't overlap with many other dates (Rails)

Posted: 14 Mar 2016 03:23 AM PDT

What I'm trying to do is pretty complicated, but bear with me. I am using Rails, ActiveRecord, Postgres.

Events have many locations and have many start and end times. Users can assign themselves to an event.

A User can only be in one place at a time. So, on the "assign yourself to an event page", I need to only show the Events that don't have overlapping times with the User's already assigned events.

I know that you can do this with a join but I can't figure out how.

Models:

class Event < ActiveRecord::Base    has_many :locations    has_many :event_times    has_many :assignments  end    class Location < ActiveRecord::Base    belongs_to :event    has_many :event_times  end    class EventTime < ActiveRecord::Base    belongs_to :location    belongs_to :event  end    class User < ActiveRecord::Base    has_many :assignments  end    class Assignment < ActiveRecord::Base    belongs_to :user    belongs_to :event  end  

This sums up what I'm trying to do. I know it's terrible.

user_events = Assignment.where(user_id: current_user.id).pluck(:event_id)  blocked_event_times = EventTime.where(event_id: user_events)    blocked_query_string = ""    blocked_event_times.each do |bt|    blocked_query_string += "NOT( event_times.start <= '#{bt.end}'::timestamp AND event_times.end >= '#{bt.start}'::timestamp ) AND "  end  blocked_query_string += "1=1"      return Event.includes(:event_times).where(blocked_query_string).references(:event_times)  

Am I on the right track thinking I should do something like (pseudocode):

@acceptable_times = EventTime.all LEFT JOIN user's_assigned_event_times  

and then get the Events where all of the event's times are present in @acceptable_times

Rails upload files to Amazon S3 with carrierwave and fog

Posted: 14 Mar 2016 04:28 AM PDT

I tried to upload movie files from my rails application to Amazon S3. First I tried paperclip, but it dosn't worked ...

No I tried carrierwave + fog but same result nothing worked, no files stored in S3 no database entry and no errors ...

My Files look like this:

app/uploader/movie_uploader.rb

class MovieUploader < CarrierWave::Uploader::Base     storage :fog     def store_dir           "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"     end   end  

config/initializers/carrierwave.rb

CarrierWave.configure do |config|    config.fog_credentials = {        provider:               'AWS',        aws_access_key_id:      '--',        aws_secret_access_key:  '--',        region:                 'eu-central-1'    }      config.fog_directory    = 'movies'  end  

app/models/movie.rb

class Movie < ActiveRecord::Base     mount_uploader :movie, MovieUploader  end  

app/controller/movies_controller.rb

class MoviesController < ActionController::Base    layout "application"       # Method to add a new Movie     def addMovie     if request.post?        @movie = Movie.new(movies_params)          if @movie.save            redirect_to :addMovie         end      else        @movie = Movie.new      end     end      private    def movies_params       params.require(:movie).permit(:movietitle, :movieprice, :locked, :moviedescription, :currency, :language, :movie)    end  end  

upload form

normal multipart form_tag

    <%= form_for Movie.new, :html => {:multipart => true, :class => "form-horizontal", :role => "form"}, :method => :post, :url => {} do |f| %>  

with file field

    <div class="form-group">        <label><%= f.label :movie %></label>        <%= f.file_field :movie, :class => "form-control", :placeholder => :movie %>      </div>  

I used this tutorial: https://u.osu.edu/hasnan.1/2014/03/13/rails-4-upload-image-to-s3-using-fog-and-carrierwave/

Whats going wrong?

No comments:

Post a Comment