Sunday, January 15, 2017

acts_as_followers and friendly_id gems not finding id | Fixed issues

acts_as_followers and friendly_id gems not finding id | Fixed issues


acts_as_followers and friendly_id gems not finding id

Posted: 15 Jan 2017 07:46 AM PST

Im using the acts_as_follower gem and friendly_id gem.

Iv set up acts_as_follower and everything is working as it should, I am able to follow Profiles as required. But now I have added the friendly_id gem to show profiles urls as profile/myname rather than profile/1.

But now the acts_as_follower gem doesn't work, it can't find the profile id to follow:

This is the set up what I'm trying now, but this still does not work.

  def follow      @profile = Profile.find(params[:profile_id])      current_user.follow(@profile)      redirect_to :back    end      def unfollow      @profile = Profile.find(params[:profile_id])      current_user.stop_following(@profile)      redirect_to :back    end  

Before it was:

@profile = Profile.find(params[:id])  

The error I'm getting is:

Couldn't find Profile with 'id'=  

There params that are being passed are:

{"id"=>"gurmukh-singh"}   

the id its now looking for is the friendly url name

Also the new friendly_id version requires i find profiles like this:

def set_story    @profile = Profile.friendly.find(params[:id])  end  

layout of nested form records, grouped and sorted

Posted: 15 Jan 2017 07:30 AM PST

The standard rails way to call nested forms where equipment has_many :regularitems and accepts_nested_attributes_for :regularitems is via

<%= f.fields_for :regularitems do |regularitem| %>  

This generates n replications, based on the controller build command, or the number of children in existence. However, if various groupings are required

<% @regularitems_for_section = @regularitems{ |i| i.section_id == equipment.section.id } %>    <% @sections.each do |section| %>      <%= section.name %>      <%= f.fields_for :regularitems do |regularitem| %>      <% @regularitems_for_section = @regularitems{ |i| i.section_id == equipment.section.id } %>        <%= regularitem.check_box :completed %>  

The number of records handled is a square of the number of regularitems (multiplied by itself). Is there any way to use the helpers in a way that allows such groupings; if not, how can this structure be maintained to allow editing of the nested records? Note: the above is a simplified version, as there would be two levels of [ahem] nested groupings

rspec test fails code in rails controller

Posted: 15 Jan 2017 07:47 AM PST

In my application_controller.rb, i have a line of code as follows:

def index   CaseStatus.order(:application_source).pluck(:application_source).uniq!  end  

In my rspec code, i have a line of code that visits the index path of application_controller as follows

visit applications_path  

When i run the code directly, it works perfectly but when it visits application_controller.rb via rspec, i get an error which says

NoMethodError:    undefined method `compact' for nil:NilClass  

Not sure while i get this error via rspec and capybara but if i run the code as

def index   CaseStatus.order(:application_source).pluck(:application_source)  end  

It executes perfectly with no errors. Kinda confused what the uniq! breaks in the code that suddenly the result becomes nil.

i get this error

 Failure/Error: @application_channels = CaseStatus.order(:application_source).pluck(:application_source).uniq!.compact if CaseStatus.order(:application_source).present?     NoMethodError:     undefined method `compact' for nil:NilClass   # ./app/controllers/loan_applications_controller.rb:53:in `index'  

localization of paths in spree

Posted: 15 Jan 2017 07:16 AM PST

I am adding new pages to my Spree application, (via spree_static_content and spree_contact_us). However the link to these pages is not getting the proper locale(the link is localhost:3000/contact-us instead of localhost:3000/es/contact-us). Where can I set it? I have messed around with routes but without any luck. I am interested in understanding how is the locale inserted into the path. I am using spree-i18n as localization gem for spree.

Nested fields causing rollback

Posted: 15 Jan 2017 06:43 AM PST

So I am facing this problem where nested field is causing a rollback on submit. I am using rails 5.

Here is the new and create actions of the controller

 def new      @match = Match.new      @match.heros.build   end     def create      @match = cur_user.matches.build(matches_params)      @match.save    end  

Here are the params

    def matches_params         params.require(:match).permit(:map, heros_attributes: [:id, :hero])      end  

Simplified form_for

= form_for(@match) do |f|      = f.label :map, value: "Map Played:"      = f.select "map",      [["Select Map", 0]        = f.label :heros, value: "Hero Played:"      = f.fields_for :heros do |h|        = h.select "hero",        [["Select Hero", 0]      = f.submit "Submit"  

In match.rb I have

has_many :heros, dependent: :destroy  accepts_nested_attributes_for :heros  

and in hero.rb I have

belongs_to :match  

I get a rollback on pressing submit and on running @match.errors.full_messages I get ["Heros match must exist"]

Any help would be greatly appreciated.

Edit: Views are in haml.

ruby on rails rails new error gem install ffi -v

Posted: 15 Jan 2017 06:19 AM PST

good day Today starting to study ruby on rails I find this error when creating a new application

/Users/Manux/.rvm/gems/ruby-2.1.1/extensions/x86_64-darwin-14/2.2.0-static/ffi-1.9.17/gem_make.out

An error occurred while installing ffi (1.9.17), and Bundler cannot continue. Make sure that gem install ffi -v '1.9.17' succeeds before bundling.

I use ruby-2.1.1 and rails 5.0.1

Why does d3_rails gem need <script src="https://d3js.org/d3.v4.min.js"></script>?

Posted: 15 Jan 2017 05:23 AM PST

I am learning D3.js in order to replace Highcharts in my application, so it can be released under GPL license. Here is how I installed it:

1 - I declare the d3_rails gem in the Gemfile

gem 'd3_rails'  

2 - I require d3 in the application.js file

//= require d3  

The call to d3.js methods (from within a RoR partial) did not work until I add this to the partial:

<script src="https://d3js.org/d3.v4.min.js"></script>  

Why do I have to declare this again here? Thanks for your help.

Params of multiple choice test

Posted: 15 Jan 2017 05:17 AM PST

I have a view using form which acts like multiple choice test, so there might be more then one correct answer.

What I need to do is create param containing array of arrays that lets me easily iterate through it in controller.

For now I am using erb which produce param looking like this:

params[:test][:task[index]][array consisting of correct answers]  

For example:

params[:test][:task0][10,5,"onion"]  params[:test][:task1][4,3,-120]  params[:test][:task2]["yes"html","css"]  

Where task1 is first question, task2 is second question and consist of array with answers chosen by user.

To iterate through that I would have to use metaprograming, but it's the last thing I would like to do.

Code of my view:

<% provide(:title, t(:quiz)) %>  <div class="center jumbotron">    <h2><%= t(:quiz) %></h2>    <div>      <%= form_for(:test, url: quiz_path) do |f| %>        <% @quiz.tasks.each_with_index do |task, index| %>          <div class="control-group">            <% @task = Task.find_by(id: task) %>            <%= @task.text %>            <% answers = @task.correct_answers + @task.wrong_answers %>            <% answers.shuffle! %>            <fieldset>              <% answers.each do |answer| %>                <div class="checkbox">                  <%= f.check_box("task][#{index}", {class: "checkbox", multiple: true}, answer, nil)%>                  <%= f.label "task#{index}", answer %>                </div>              <% end %>            </fieldset>          </div>        <% end %>        <%= f.submit t(:finish_quiz), class: "btn btn-lg btn-primary" %>      <% end %>    </div>  </div>  

So the question is: do you know more elegant and optimal way to do it?

Do I have to use metaprogramming?

Rails ActionMailer incorrect param value of message attachment part

Posted: 15 Jan 2017 07:40 AM PST

Mailer code which send message with attachment file:

class OutgoingMailer < ActionMailer::Base    include Roadie::Rails::Automatic      layout 'mails/outgoing'      def send_mail(mail_account_id, to, subject, body_data, attach_params=nil)      mail_account = MailAccount.find(mail_account_id)        delivery_options = {***}        attachments['my_file.png'] = {        content: File.read("#{Rails.root}/tmp/my_file.png")      }        headers['Message-ID'] = "<#{SecureRandom.uuid}@#{mail_account.address.gsub('@','.')}>"        message = mail(to: to, from: mail_account.address, body: '', subject: subject, content_type: "multipart/mixed", delivery_method_options: delivery_options)        html_alternative = Mail::Part.new do        content_type 'text/html; charset=UTF-8'        body body_data      end        message.add_part html_alternative    end  end  

When I open this message in the mail web-client (mail.yandex.ru) that it does not show the number of attachments, example:

web-client example

So, I compared correct and incorrect message parts:

correct

<struct Net::IMAP::BodyTypeMultipart media_type="MULTIPART", subtype="MIXED", parts=[       <struct Net::IMAP::BodyTypeText media_type="TEXT", subtype="HTML", param={"CHARSET"=>"utf-8"}, content_id=nil, description=nil, encoding="7BIT", size=32, lines=1, md5=nil,  disposition=nil, language=nil, extension=nil>,        <struct Net::IMAP::BodyTypeBasic media_type="IMAGE", subtype="PNG", param={"NAME"=>"my_file.png"}, content_id="<12sdf647_3gh4253ff456@temp.mail>", description=nil, encoding="BASE64", size=367834, md5=nil, disposition=nil, language=nil, extension=nil>    ], param=nil, disposition=nil, language=nil, extension=nil>  

incorrect:

<struct Net::IMAP::BodyTypeMultipart media_type="MULTIPART", subtype="MIXED", parts=[      <struct Net::IMAP::BodyTypeText media_type="TEXT", subtype="HTML", param={"CHARSET"=>"UTF-8"}, content_id=nil, description=nil, encoding="7BIT", size=32, lines=1, md5=nil, disposition=nil, language=nil, extension=nil>,       <struct Net::IMAP::BodyTypeBasic media_type="IMAGE", subtype="PNG", param=nil, content_id="<587b45f51f468_36c67182b4c247a5@temp.mail>", description=nil, encoding="BASE64", size=367834, md5=nil, disposition=nil, language=nil, extension=nil>    ], param=nil, disposition=nil, language=nil, extension=nil>  

As you can see the incorrect message has param=nil for Net::IMAP::BodyTypeBasic object.

How I must send message with correct param value of attachment part?

Typeahead.js to search through Users with Ruby on Rails

Posted: 15 Jan 2017 05:01 AM PST

I am kinda new to Ruby on Rails. In my application there are users and I want users to search for another users by their name, username, surname etc. I am using typeahead.js from the source https://twitter.github.io/typeahead.js/ Somehow when I hit enter on the search bar nothing happens. All i got is a question mark like this http://localhost:3000/home? any help would be appreciated. Thanks!

I have this on my routes.rb

get '/users/typeahead/:query' => 'users#typeahead'

gemfile

  gem 'twitter-typeahead-rails'

app/assets/javascripts/application.js

//= require typeahead

app/assets/javascripts/users.js

        var onReady = function() {          // initialize bloodhound engine        var searchSelector = 'input.typeahead';          var bloodhound = new Bloodhound({          datumTokenizer: function (d) {            return Bloodhound.tokenizers.whitespace(d.value);          },          queryTokenizer: Bloodhound.tokenizers.whitespace,            // sends ajax request to remote url where %QUERY is user input          remote: '/users/typeahead/%QUERY',          limit: 50        });        bloodhound.initialize();          // initialize typeahead widget and hook it up to bloodhound engine        // #typeahead is just a text input        $(searchSelector).typeahead(null, {          displayKey: 'name',          source: bloodhound.ttAdapter()        });          // this is the event that is fired when a user clicks on a suggestion        $(searchSelector).bind('typeahead:selected', function(event, datum, name) {          //console.debug('Suggestion clicked:', event, datum, name);          window.location.href = '/users/' + datum.id;        });      };    

I have typeahead.js in the following place

vendor/assets/javascripts/typeahead.js

My User Model user.rb

    def search_name_like    search.where("name ILIKE ?", "%#{name_like}%")  end    def search_typeahead    search.where("name ILIKE ?", "%#{typeahead}%")  end    

And the controller users_controller.rb

        # GET /users        # GET /users.json        def index          @search = User.new(search_params)          @users = search_params.present? ? @search.results : User.all        end          # GET /users/typeahead/:query        def typeahead          @search  = User.new(typeahead: params[:query])          render json: @search.results        end          private          def search_params          params[:user] || {}        end    

the view is like _nav_user.html.erb layouts/_nav_user.html.erb

          div class="form-group"              input class="typeahead" type="text"      /div    

Polymorphic for storing information about several objects/entities at a time

Posted: 15 Jan 2017 05:20 AM PST

Say, I have a model Activity. And I want to use it as a model for kind of news or event happening on my website such:

a user has created an article

a user has edited an article

a user has deleted a comment

a user has uploaded a picture

There always be a connection to a User. And to something else: Article, News, Comment, Picture, Profile. How can I implement this? I can do this:

Activity    belongs_to :with_activity, polymorphic: true    belongs_to :user         Articles     has_many :activities, as :with_activity      News     has_many :activities, as :with_activity   

But when I'm creating an activity, how would I specify all the IDs involved?

For example: "A user has added a comment for an article". There're 3 entities here. User id is captured via "belongs_to :user". But either Comment ID or Article is captured via "belongs_to :with_activity, polymorphic: true" and not both. Whereas I want both. Or more if needed:

"A user has added a comment for a picture of an article". -- 4 entities, but only IDs of 2 of them are captures. I need to store all their IDs. "polymorphic" allows to store only an ID of a single entity.

How can I get around of that? Should I add "belongs_to" :picture, :article, :comment and so to Activity? Is there a better solution?

Note that I don't want to use a gem for that.

Ruby on Rails: Why Isn't My Nested Form Working?

Posted: 15 Jan 2017 04:47 AM PST

I have followed the RailsCast video into creating nested forms: http://railscasts.com/episodes/196-nested-model-form-part-1?autoplay=true

But for some reason it isn't saving.

When creating an email I am trying to create records in the recipients table, so that it can be recorded which groups and contacts the email was sent to. This works but I am also trying to save data to a column called "message" in this table, but for some reason the new record in the recipients table is made but the message is not saved in the table.

My models are:

class Email < ActiveRecord::Base        belongs_to :account      has_many :recipients      has_many :contacts, through: :recipients, :dependent => :destroy      has_many :groups, through: :recipients, :dependent => :destroy        accepts_nested_attributes_for :recipients  end  class Recipient < ActiveRecord::Base       belongs_to :email     belongs_to :contact     belongs_to :group    end  

My emails_controller new and create methods are:

def new      @email = Email.new      @email.recipients.build      @useraccounts = Useraccount.where(user_id: session[:user_id])  end    def create      @email = Email.new(email_params)      if @email.save          redirect_to @email      else          render 'new'      end  end  private  def email_params      params.require(:email).permit(:subject, :account_id, { contact_ids: [] }, { group_ids: [] }, recipient_attributes: [:message])  end  

And my _form.html.erb is

<%= form_for @email do |f| %>      <% if @email.errors.any? %>      <div id="error_explanation">        <h2>          <%= pluralize(@email.errors.count, "error") %> prohibited this email from being saved:        </h2>        <ul>          <% @email.errors.full_messages.each do |msg| %>            <li><%= msg %></li>          <% end %>        </ul>      </div>    <% end %>    <p>      <%= f.label :account_id, "Send from account" %><br>      <% @useraccounts.each do |useraccount| %>          <%= f.radio_button :account_id, useraccount.account_id, :checked => false %>          <%= f.label :account_id, useraccount.account.email, :value => "true"  %><br>      <% end %>    </p>      <p>      <%= f.label :subject %><br>      <%= f.text_field :subject %>    </p>      <p>      <%= f.label :contacts, "Send to Contacts:" %><br>      <%= f.collection_check_boxes :contact_ids, Contact.where(user_id: session[:user_id]), :id, :firstname ,{ prompt: "firstname" } %>    </p>     <p>      <%= f.label :groups, "Send to Groups:" %><br>      <%= f.collection_check_boxes :group_ids, Group.where(user_id: session[:user_id]), :id, :name ,{ prompt: "name" } %>    </p>       <%= f.fields_for :recipients do |t| %>      <%= t.label :message %>      <%= t.text_field :message %>    <% end %>    <p>      <%= f.submit %>    </p>    <% end %>  

Can someone please help me work out why the message field is not being saved in the recipients table whilst a new row is being created in the table?

applescript error passing a 'rails runner' second command in a do shell script

Posted: 15 Jan 2017 04:13 AM PST

I am running

 do shell script "cd path_to_my_rails_application; rails runner Model.action"   

Works fine if I manually enter the commands in terminal and it also works if i set the commands in a window terminal like

tell application "Terminal"  activate       do script "" in window 1  end tell  

Though i want to use the applescript output, and doing do shell script "" seems to get me what I need. Im unable to get the output any other way. unfortunately I keep getting this error:

 Rails is not currently installed on this system.  

This question looks very similar to my problem with this answer

 do shell script "eval `/usr/libexec/path_helper -s`; echo $PATH"   

related to loading "sh" environment instead of user's. But I cant seem to get the path/command working.

Disable pjax in rails_admin

Posted: 15 Jan 2017 04:16 AM PST

I use the rails_admin gem, and without adding any custom javascript to it, I get Cannot read property 'push' of undefined coming from rails_admin's javascript.

$.event.props.push('state') // line causing the error  

Any idea on how to fix this ? It causes my tests to fail.

It look like this could be caused by pjax (from what I read on some SO posts). I tried disabling it using:

register_instance_option :pjax? do    false  end  

But it fails in:

RailsAdmin.config do |config|    end  

Where am I supposed to add it ?

Any input will be much appreciated !

How to properly work with the Memcached?

Posted: 15 Jan 2017 03:56 AM PST

There are RoR project on Ubuntu server. I installed on the operating system Memcached:

sudo apt-get install memcached  

And also for Ruby was installed gem dalli.

Configuration for production:

config.cache_store = :dalli_store  config.action_controller.perform_caching = true  

As for caching, then I'm basically apply the caching fragment in cycles. For example, the caching news, I implemented as follows:

<% @news.each do |news| %>      <% cache news do %>          # Тут поля из news      <% end %>  <% end.empty? and begin %>      <p class="lead"><%= t('news.text.no_news') %></p>  <% end %>  

As for the caching in action show. In fact, in the template file show.html could also apply the the caching of fragment, but I will implement the caching as follows:

fresh_when last_modified: @news.updated_at.utc, strong_etag: @news  

I searched in google and found many examples of implementation, but still adhered to the official documentation (official examples) of Rails.

Memcached server is specified as localhost specifically - I do not have the possibility to take a separate server for the cache.

I am interested in Expert opinion: I did everything right? What are the pros and cons of the current implementation of the cache?

Rails Job Doesn't Proceed after rails jobs:work

Posted: 15 Jan 2017 04:13 AM PST

I have a job in my rails app which I was running it before like a charm with this command:

rails jobs:work  

but it doesn't proceed any longer.I killed the processes and tried a lot of solutions but nothing happened! What I guess is that this job has generated a queue so that it can not be running any more! Could you please help me? Thanks in advance. It stops in this situation :

bundle exec rake jobs:work  [Worker(host:afsane pid:7517)] Starting job worker  

and my job :

class LdapSyncJob < ApplicationJob    queue_as :default    require 'pp'    def perform     ....    end  end  

FYI

ps aux | grep rails    afsane    7675  0.0  0.0  15764   968 pts/5    S+   15:24   0:00 grep --color=auto rails  

Tuples from Postgres not getting extracted onto the webpage using rails

Posted: 15 Jan 2017 05:23 AM PST

I'm trying to develop a simple blog app using rails 5.0.1 and Postgres The problem is that,although 3 tuples are stored in the db (I checked it), when I extract it using "@posts=Post.all "command, only 3 horizontal lines occur(I.e the 3 tuples are scanned but not displayed). The code :

<% @posts.each do |post| %>  <h3> <%= post.title %></h3><hr/>  <p><%= post.body %></p>  <% end %>  

The index view:enter image description here The Postgres DB: enter image description here

adding react-big-calendar will cause Uncaught TypeError: Cannot read property 'matches' of null

Posted: 15 Jan 2017 02:46 AM PST

reproducing repo

https://github.com/github0013/ror_rbc/commit/246f6e1839cdd6aababeeacb9301a80b040e453d

# git clone, then  bundle && npm install   foreman start -f Procfile.dev # should start the server at http://localhost:3000/hello_world  

problem

I am using
https://github.com/shakacode/react_on_rails
to build a web app, but if I try to import BigCalendar from 'react-big-calendar' in a jsx file, it gives the error in the title.

things I checked

https://github.com/intljusticemission/react-big-calendar
this library uses
https://github.com/react-bootstrap/dom-helpers
and
https://github.com/react-bootstrap/dom-helpers/blob/master/src/query/matches.js#L7
this line document.body is null as far as I checked.

why document is null?

I am quite new to reactjs, webpack and etc, so I am sure I am missing some basic knowledges, but if anyone can point out why document object is missing, please let me know.

ransack match all associations

Posted: 15 Jan 2017 02:56 AM PST

I have User model, has_many skills. I need to get users match all the selected skills. For example:

User A: Ruby, HTML, JavaScript.   User B: Ruby  User C: Ruby, C++  

When I search using the list of skills names or ids. I need get users have all values in this list. So, Search using Ruby & Javascript, I need to get User A.

The Problem if I used ransack gem skills_id_in, It'll return all users have Ruby Skill. The Query is as the following:

SELECT \"users\".* FROM \"users\" LEFT OUTER JOIN \"user_skills\" ON \"user_skills\".\"user_id\" = \"users\".\"id\" LEFT OUTER JOIN \"skills\" ON \"skills\".\"id\" = \"user_skills\".\"skill_id\" WHERE \"skills\".\"id\" IN (1, 3)  

If it's not allowed in ransack. Can you help How make it in ActiveRecord & run in DB level?

My Opinion: It's can't implement using ransack params, If you know Native Query to match all association, let me know?

ActiveRecord's serialize converts integers to strings? [Rails]

Posted: 15 Jan 2017 02:48 AM PST

When I am persisting a hash as a JSON, I expect the hash to be converted to JSON and not modified, but instead the keys are changed from integer to string.

The model:

class Shift < ActiveRecord::Base    serialize :api_returns, JSON  end  

Usage:

> Shift.create(api_returns: { 123 => '456' })    SQL (0.5ms)  INSERT INTO "shifts" ("api_returns") VALUES ($1) RETURNING "id"  [["api_returns", "{\"123\":\"456\"}"]]  => #<Shift:0x007fe785038c60 id: 22, ... api_returns: {"123"=>"456"}>  

Any ideas how to make ActiveRecord not mangle my input?

why the vagrant windows can ping but can't access in the browser

Posted: 15 Jan 2017 05:33 AM PST

i spend a hold day to build the vagrant env on the windows ,and use the rbenv build the ruby env & install the rails !

evrythings ok,but when i start the rails s found i can't access on the chrome,then i use the ubuntu links to ping the 127.0.0.1:3000 it's ok,but ping the 192.168.10.10:3000 told me the connection refused!

enter image description here

that's my vagrantfile setting ,just only setting the private_network ip

anyone else can tell me how to resolv the problem?

Update <li> element class with Javascript for rails loop

Posted: 15 Jan 2017 04:08 AM PST

I'm designing an application to store sport games. Now in my notifications I have a list of games to confirm, in my list I have the read and unread class options and also an action to confirm the game. Now when someone confirms a game I don't want a page refresh, however the class should change in read and the button should disappear.

    <ul class="notification-body">        <% @games.each do |game|                       #CONTROLE OP VERWIJDERDE USERS                        home_user_name = if game.home_user.present?                          game.home_user.username                      else                           t :deleted_user                       end                         away_user_name = if game.away_user.present?                          game.away_user.username                      else                           t :deleted_user                       end       %>            <!-- LOST GAMES -->              <li class="unread">                  <span>                  <p class="msg">                      <% if game.home_user.avatar_url.present? %>                          <%= image_tag(game.home_user.avatar_url, class: 'air air-top-left margin-top-5', width: '50', height: '50') %>                      <% elsif game.home_user.uid.present? %>                          <%= image_tag(game.home_user.largeimage, class: 'air air-top-left margin-top-5', width: '50', height: '50') %>                      <% else %>                          <%= image_tag(asset_path('picempty.jpg'), class: 'air air-top-left margin-top-5', width: '50', height: '50') %>                      <% end %>                              <span class="from"><% if game.loser_user == game.home_user %>Game Won<% else %>Game Lost<% end %> </span>                            <time><%= time_ago_in_words(game.created_at) %> ago</time>                            <span class="subject"><%= home_user_name %> <% if game.loser_user == game.home_user %> lost <% else %>won  <% end %> the game with  <%= game.home_score %> - <%= game.away_score %></span>                                <span class="msg-body">                                     <%= link_to  game_confirm_game_path(game, game.id), method: :patch, class: "msg", remote: true do %>                                        <button class="btn btn-xs btn-success margin-top-5"> <i class="fa fa-check" aria-hidden="true"></i> Confrim</button>                                  <% end %>                                   <%= link_to game_conflict_game_path(game, game.id), method: :patch, class: "msg", remote: true do %>                                        <button class="btn btn-xs btn-warning margin-top-5"> <i class="fa fa-flag" aria-hidden="true"></i> Flag</button>                                  <% end %>                             </span>                  </p>                            </span>              </li>        <% end %>  </ul>  <% content_for :scripts do %>    <script>    $('li a').click(function () {     // remove existing active class inside li elements     $('li.unread').removeClass('unread');    // add class to current clicked element     $(this).addClass('read');  });    </script>  <% end %>  

Could someone help me with this Javascript? I kind of a noob in Javascript so sorry if this is a stupid question.

A little recap:

When

<%= link_to  game_confirm_game_path(game, game.id), method: :patch, class: "msg", remote: true do %>    <button class="btn btn-xs btn-success margin-top-5"> <i class="fa fa-check" aria-hidden="true"></i> Confrim</button>    <% end %>  

This button is clicked, it should disappear and also

<li class="unread">  

should change to

<li class="read">  

Using Rails 5 enum with PG array

Posted: 15 Jan 2017 01:27 AM PST

I'm trying to use Rails' enum with PostgreSQL's array column.

class Post < ActiveRecord::Base    enum tags: { a: 0, b: 1, c: 2 }, array: true  end  

However the above code does not work.

Is there any way to using enum on array column like arrtibute supporting array: true?

Show bootstrap modal after successful save to db

Posted: 15 Jan 2017 01:15 AM PST

I have a basic email entry form on my home page, and if the subscriber's email is saved I want to redirect them back and display a bootstrap modal. I've thought about sending a flash[] or session[] to the view and then saying, "If flash / session, display modal," but I'm not sure how to actually trigger the modal.

Basically, I'm wondering two things:

  • How to tell the view that the DB insert was successful.
  • How to trigger the bootstrap modal using this info.

/controllers/subscribers_controller.rb:

def create    @subscriber = Subscriber.new(subscriber_params)    if @subscriber.save      # Send info to view (a flash?) saying to show modal      redirect_to root_path  ...  

explain to me how this path works and what these error messages mean?

Posted: 15 Jan 2017 12:09 AM PST

here is the route:

get 'tags/:tag', to: 'photos#index', as: :tag  

which gives url www.example.com/tags/food

I figured out that the correct path is

<%= link_to 'Food', tag_path(:tag => "food") %>   
  1. why do i have to put quotations around food, turning it into a string?

  2. why does tag_path(tag: "food") return the error:

(undefined method `stringify_keys' for "/tags/food":String):

if i just do tag_path(tag: food) i get an error:

ActionView::Template::Error (undefined local variable or method `food'

  1. is it actually possible to pass a method from the controller into the path? that sounds cool. can you give me an example of such a method?

Migration css rails login form to bootstrap

Posted: 15 Jan 2017 01:27 AM PST

Need help migration to bootstrap.

bootstrap sound easy just go get all scss and samples to paste. But I don't know how to insert "@user, url: signup_path" into/or replace in bootstrap code to work in rails app.

html:

<div class="row">  <div class="col-md-6 col-md-offset-3">    <%= form_for(@user, url: signup_path) do |f| %>      <%= render 'shared/error_messages' %>      <%= f.label :name %>    <%= f.text_field :name %>      <%= f.label :email %>    <%= f.email_field :email %>      <%= f.label :password %>    <%= f.password_field :password %>      <%= f.submit "Create my account", class: "btn btn-primary" %>  <% end %>  </div>  </div>  

Bootstrap code: from getbootstrap

<div class="input-group input-group-lg">    <span class="input-group-addon" id="sizing-addon1">@</span>    <input type="text" class="form-control" placeholder="Username" aria-describedby="sizing-addon1">  </div>    <div class="input-group">    <span class="input-group-addon" id="sizing-addon2">@</span>    <input type="text" class="form-control" placeholder="Username" aria-describedby="sizing-addon2">  </div>    <div class="input-group input-group-sm">    <span class="input-group-addon" id="sizing-addon3">@</span>    <input type="text" class="form-control" placeholder="Username" aria-describedby="sizing-addon3">  </div>  

What is :format in rails rake routes? [duplicate]

Posted: 14 Jan 2017 10:34 PM PST

This question already has an answer here:

What does the format below stand for? I know it's not necessary but what is it referring to?

articles GET    /articles(.:format)          articles#index  

Rails Google Calendar API

Posted: 14 Jan 2017 10:26 PM PST

First time trying to use the google calendar gem in my rails app. What I am hoping to do is Post to the google calendar API's 2 users or email addresses of some sort and then try to find a free/busy schedule for both emails.

One of the emails will be authenticated through oauth and the other emails calendar is normally visible to the user who has been authenticated.

Is this possible? Any advice or pointers in the right direction are greatly appreciated!

Tyler

how to autofill the textfield tag in new.html.erb and save to database using create action

Posted: 14 Jan 2017 10:34 PM PST

I've been able to autofill my text field tags but if i hide them by doing <% instead of <%= they dont save to my database any suggestions?

    <%= @low["lowest_price"] %>        <%= form_tag "/bids", method: :post do %>        <div>        <%= label_tag :bid, "place your bid "   %>        <%= text_field_tag :bid %>        </div>        <div>        <% label_tag :event %>        <% text_field_tag :event_id, params[:id] %>        </div>           <div>         <% label_tag :user_id %>         <% text_field_tag :user_id, current_user.id %>         </div>           <div>         <%= label_tag :lowest_price %>         <%= text_field_tag :lowest_price, @low["lowest_price"] %>         </div>         <%= submit_tag "Submit" %>           <% end %>  

Heres the create action in the bid controller that this form is connected to

     def create       @bidd = Bid.new(event_id: params[:event_id], user_id:               params[:user_id], bid: params[:bid], lowest_price:               params[:lowest_price])       if session[:user_id] == current_user.id     @bidd.save     flash[:success] = "bid created."     redirect_to "/users/#{current_user.id}"  else     flash[:warning] = 'please sign in'     redirect_to '/login'   end  

heres the page the user show page where the bids will show up on which works as i said when text fields are added manually.

    <% @bidds.each do |a| %>            <p>event: <%= a.event_id %></p>            <p>Price: <%= a.bid %></p>  

Can I use Friendly Id on a Rails model without having to create a slug column on the model table?

Posted: 14 Jan 2017 11:44 PM PST

On Rails 4.2, I would like to use Friendly Id for routing to a specific model, but dont wan't to create a slug column on the model table. I would instead prefer to use an accessor method on the model and dynamically generate the slug. Is this possible? I couldn't find this in the documentation.

No comments:

Post a Comment