Monday, December 19, 2016

Debugging a rake task that is calling a controller action | Fixed issues

Debugging a rake task that is calling a controller action | Fixed issues


Debugging a rake task that is calling a controller action

Posted: 19 Dec 2016 08:16 AM PST

I have the following rake task...

task :demote_sausages => :environment do      session = ActionDispatch::Integration::Session.new(Rails.application)    puts "this is the demote sausages task"    actions = UserAction.where action_date: Time.now.yesterday.strftime("%m/%d/%Y")    actions.each do |a|      session.post "/demote_sausage", {user_id: a.user_id}    end  end  

...and here is the controller action...

  def demote_sausage      puts "made it to controller action"      @z_options[:body][:id] = params[:user_id]      @z_options[:body][:type] = 1      HTTParty.post("https://api.blah.org/v1/user/update", @z_options)    end  

My issue is, I am not sure if I am making it to my controller action or not. I am seeing the puts message in the rake task, but I am NOT see the puts in the controller action (but maybe I shouldn't?).

Any tips on how to debug what is going on in the controller?

Rails Watir Webdriver - select option not working

Posted: 19 Dec 2016 08:15 AM PST

I'm writing a web scraper in Rails and can't Watir to select an option from a select tag. I've tried multiple variations but by all accounts this should work:

browser.select_list(:id, "system").select("PC")  

I've tested to make sure both the select box and value are present, I've used sleep to delay the click to allow everything to load, I've used .when_present, I've tried it in pry (I can set and unset checkboxes in pry and see the effect live, not the case with the select box) and I'm out of ideas. There's no error messages, it just doesn't do anything.

Here's the full code:

require 'watir-webdriver'  require 'pry'    browser = Watir::Browser.new  browser.goto 'http://www.co-optimus.com/games.php'    browser.div(id: "system-modal").link(class: "close-reveal-modal").click    sleep 5  browser.select_list(:id, "system").when_present.select("PC")    sleep 1  browser.checkbox(id: "couch").when_present.set    sleep 2  browser.link(text: "Find Games").when_present.click  

Ruby Rails insert ActiveRecord query in my model

Posted: 19 Dec 2016 08:07 AM PST

So I'm trying to perform a query of "SpiritTrial" model where "trlid" have 7th and 8th digit = "TI", then I want to insert the objects it finds into model TiTrial and I would like to take the "trlid" from the SpiritTrial model and redefine it as "name" in TiTrial. Here's where I'm at in TiTrial.rb I'm getting the right stuff back I'm just having a hard time translating the documentation out there in to what I need it to do....any help is super appreciated as always.

def spiritpull    u = SpiritTrial.where("trlid LIKE (?)", "%%%%%%TI%")    end  

Rails: association build with index

Posted: 19 Dec 2016 08:13 AM PST

In my edit action I do something like this

def edit    @user = User.find(params[:id])    applications = @user.applications    if !applications.where(general1: true).present?      @user.applications.build    end    if !applications.where(general2: true).present?      @user.applications.build    end  end  

Now is there any way to specify the index of the build, so that I can do something like this

  if !applications.where(general1: true).present?      @user.applications.build(index: 2)    end    if !applications.where(general2: true).present?      @user.applications.build(index: 1)    end  

So basically I want to specify build index of the nested form.

rails server -e production is giving error

Posted: 19 Dec 2016 07:56 AM PST

I am trying to run a rails application locally. After setting > >

config.assets.compile = true  config.assets.precompile += %w( *.css *.erb *.scss *.js *.coffee *.png *.jpg *.ico *.gif)  

in production.rb file. I run rake assets:precompile RAILS_ENV = production and it runs successfully.

Then i run rails s -e production that is giving error

C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-4.2.4/lib/act ive_support/dependencies.rb:274:in `require'

  • I am using windows 8.1

ActiveRecord one connection per request

Posted: 19 Dec 2016 07:43 AM PST

I have an application that let the user to connect in multiples environments. Depending of the choice of environment that the user pick, activerecord will use Database X or Y.

But when I use ActiveRecord::Base.establish_connection, activerecord change the database for all users. I want that user 'A' use Database 'X' and user 'B' use Database 'Y' at the same time in one single application. Is that possible with rails?

apply css class to a div without js

Posted: 19 Dec 2016 08:06 AM PST

I am displaying some nested comments recursively in my app but ran into a challenge of apply a specific class when there are no nested comments. How can I cleanly apply the class sole to my div entry only when nested_commments is > 0 ?

    def horizontal_tree_for(comments)          comments.map do |comment, nested_comments|         entry(comment) +             (nested_comments.size > 0 ?                          content_tag(:div, horizontal_tree_for(nested_comments), class: "branch") +              "</div>"              : "</div>")      end.join.html_safe    end    def entry(comment)    "<div class='entry'  **conditional sole class**><span class='label'> #{comment.name} </span>"  end  

Selecting unique values of keys inside postgresql json field

Posted: 19 Dec 2016 07:21 AM PST

I have the following model:

Shipment:    reference_numbers: [] :json field  

reference fields general structure is as follows:

[{'reference_field_name': 'freight_number', 'reference_field_value': '0098'}, {'reference_field_name': 'bill_of_lading', 'reference_field_value': '1190' }]  

Here the field name can vary from delivery to delivery. It can be anything not just bill_of_lading and freight_number.

What is the best way to find all unique values of 'reference_field_name' across reference_numbers across Shipments?

Could not find 'bundler'

Posted: 19 Dec 2016 08:08 AM PST

I installed ruby and bundler but when I run bundle command I get error:

[jenkins@localhost secure_gate]$ bundle  /usr/share/rubygems/rubygems/dependency.rb:296:in `to_specs': Could not find 'bundler' (>= 0) among 8 total gem(s) (Gem::LoadError)      from /usr/share/rubygems/rubygems/dependency.rb:307:in `to_spec'      from /usr/share/rubygems/rubygems/core_ext/kernel_gem.rb:47:in `gem'      from /usr/local/bin/bundle:22:in `<main>'  [jenkins@localhost secure_gate]$  

Is there a way to save this issue?

Active Admin use related model fields in filters

Posted: 19 Dec 2016 07:54 AM PST

I have User model and Address, SocialProfile Model. I want to show the fields of Address model like "zip", "address_line_1" in the filter section of User resource in active admin.

As Address model i want to show the fields of SocialProfile Model in same resource of User. how can I show the fields in both drop-down and text search in active admin of belongs_to model?

class User < ActiveRecord::Base    has_many :addresses    has_many :social_profiles  end    class Address < ActiveRecord::Base   belongs_to :user  end    class SocialProfile < ActiveRecord::Base    belongs_to :user  end  

Filters for User resource in app/admin/user.rb

filter :mobile  filter :full_name  filter :zip #to use the address model's "zip" field  filter :source #use social_profile model's "social" field             

Rails - Visiting URLs in a rake task - Sockets Error

Posted: 19 Dec 2016 07:11 AM PST

I'm attempting to create a rake tasks that visits a series of URLs, logs the status code, and then prints them to console. My code is as follows:

require 'csv'  require 'net/http'  require "open-uri"    namespace :routes do    desc "check status codes"    task check_301s: :environment do      # open_csv      # edit_urls      generate_routes      # visit_urls      # log_status_codes      visit_and_log_routes      # give_results    end      def generate_routes      csv = CSV.open('lib/better.csv', headers: true)      @urls = []      csv.each do |row|        @urls << row['url'].gsub('foo', 'localhost:3000')      end    end      def visit_and_log_routes      responses = []      @urls.each do |url|        http = Net::HTTP.new(url, 3000)        response = http.request_get('/')        responses << response      end      puts responses    end  end  

I'm receiving the following error code when running this from terminal:

SocketError: Failed to open TCP connection to localhost:3000/children-centre/london/greenwich/eltham-childrens-centre/join:3000 (getaddrinfo: nodename nor servname provided, or not known)  

I'm not sure if there is an easier way to visit URLs and log their status code, if so please let me know how to do it, and if not then how I can correct this error message. I'm assuming I'm simply leaving out the relevant options but am not sure how / where to add them.

Ruby won't start, problems with versions

Posted: 19 Dec 2016 07:07 AM PST

it is my first day with Ruby so maybe it is a very stOOpid thing to ask, but after 0.5 of a day I am giving up. I need to run an app written in Ruby 2.2.0. first I downloaded Ruby 2.3.0., but then got 2.2.0 as well and used a rvm --default use 2.2.0 command. Still in usr/local/lib/site_ruby there is only a 2.3.0. folder and when typing sudo apt install ruby-bundler && bundler install predictably I get an error:

/usr/local/lib/site_ruby/2.3.0/rubygems.rb:270:in find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException) from /usr/local/lib/site_ruby/2.3.0/rubygems.rb:298:inactivate_bin_path' from /usr/local/bin/bundler:22:in `'

I'd be very grateful for some enlightment Ubuntu 16.04, app with Ruby 2.2.0, I have also Ruby 2.3.0

Vagrant doesnt start host

Posted: 19 Dec 2016 07:31 AM PST

I cant acces my vagrant machine via host. No Error, just no connection if I open the IP or host adress in the browser.

here the vagrant settings:

# -*- mode: ruby -*-  # vi: set ft=ruby :    VAGRANT_API_VERSION = 2    Vagrant.configure(VAGRANT_API_VERSION) do |config|    config.vm.box = 'ubuntu/trusty64'    config.ssh.insert_key = false    config.vm.network 'private_network', ip: '192.168.33.33'    config.vm.hostname = 'domain.com'    config.vm.synced_folder '.', '/opt/folder'      config.vm.provider :virtualbox do |v|      v.name = 'myname'      v.memory = 512      v.cpus = 2      v.customize ['modifyvm', :id, '--natdnshostresolver1', 'on']      v.customize ['modifyvm', :id, '--ioapic', 'on']    end      # Set the name of the VM. See: http://stackoverflow.com/a/17864388/100134    config.vm.define :myname do |myname|    end          config.vm.provision 'ansible' do |ansible|      ansible.playbook = 'provisioning/playbook.yml'      ansible.inventory_path = 'provisioning/inventory'      ansible.sudo = true    end  end  

Rails: show list of one controller inside of another controller

Posted: 19 Dec 2016 06:52 AM PST

I have a "Resources" controller and on the index I can find a list of "Articles" and "Downloads", each of which is its own controller.

  <% @resource.each do |resource| %>     <h4><%= resource.article.title %></h4>     <h4><%= resource.article.description %></h4>     <%= link_to "Read More...", article(article) %>   <% end %>  

And I made the association on the models like this:

class Article < ApplicationRecord   belongs_to :resource  end    class Download < ApplicationRecord   belongs_to :resource  end    class Resource < ApplicationRecord   has_many :articles   has_many :downloads  end  

How can I call the list of Articles and Downloads inside the Resources view, and link to them?

Rails URL for index action includes weird wording for ActiveRecord_Associations

Posted: 19 Dec 2016 07:41 AM PST

I've published a sizable update to my heroku staging site and besides some saving issues (which I'll post in a separate question), I've noticed some weird things happening to my index url.

Projects are nested under users like such: routes.rb

resources :users do    resources :projects do      get "cancel", :on => :member      post "cancel" => 'projects#cancel_save', :on => :member      get "rate_supplier", :on => :member      post "rate_supplier" => 'projects#rate_suppliers', :on => :member    end  end  

Originally when I viewed a users projects it displayed correctly as

/users/2/projects

But now for some reason the url looks as follows:

users/2/projects.%23<Project::ActiveRecord_Associations_CollectionProxy:0x007fe577ab9820>

I'm not sure why the rest of that stuff is in the url?? And can't find anything online. Help!

UPDATE

The models looks as follows: project.rb

class Project < ApplicationRecord  belongs_to :user, inverse_of: :projects  belongs_to :budget  belongs_to :industry  belongs_to :project_source  belongs_to :project_status  belongs_to :project_type, class_name: 'Project_type'  has_and_belongs_to_many :features, join_table: :projects_features  has_and_belongs_to_many :addons, join_table: :projects_addons    has_one :project_close_reason  accepts_nested_attributes_for :project_close_reason    has_one :supplier_rating  accepts_nested_attributes_for :supplier_rating    scope :open, -> {      where("project_status_id <=?", 8)  }    scope :closed, -> {      where("project_status_id >?", 8)  }    scope :cancelled, -> {      where("project_status_id =?", 10)  }    scope :completed, -> {      where("project_status_id =?", 9)  }       end  

user.rb

class User < ApplicationRecord  # Include default devise modules. Others available are:  # :confirmable, :lockable, :timeoutable and :omniauthable  devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable    validates :password, :presence => true,                   :on => :create,                   :format => {:with => /\A.*(?=.{8,})(?=.*\d)(?=.*[\@\#\$\%\^\&\+\=]).*\Z/ }  validates :email, :presence => true, :uniqueness => true    has_many :projects, inverse_of: :user  has_many :businesses, inverse_of: :user  accepts_nested_attributes_for :projects    def full_name       "#{last_name}, #{first_name}"  end      end  

And here is the link:

<li class="<%= 'active' if params[:controller] == 'projects' %>">      <%= link_to user_projects_path(current_user, @projects) do %>          <i class="fa fa-list" aria-hidden="true"></i> Projects      <% end %>  </li>  

And here is the index action in the projects controller

def index    @title = "Your Projects"    @projects = current_user.projects  end  

`require': incompatible library version

Posted: 19 Dec 2016 06:57 AM PST

I'm using RVM as version management for Ruby and installed Ruby 2.2.5. The bundle is installed completely and successfully. But when I started the rails server using rails s it is giving me 'require': incompatible library version (LoadError) for pg.

I tried re-installation of rvm many times. Cleaned the gemset but the issue still persists.

I'm getting the following error again and again:

.rvm/gems/ruby-2.2.5/gems/pg-0.19.0/lib/pg.rb:4:in `require': incompatible library version - /home/user/.rvm/gems/ruby-2.2.5/gems/pg-0.19.0/lib/pg_ext.so (LoadError)  

Any help will be highly appreciated.

Ruby on Rails - Save current datetime to database [SOLVED]

Posted: 19 Dec 2016 07:55 AM PST

When a user created an account the current datetime has to be send to the database. I got a column with for example "a_started_at".

Controller:

def create  .......     if @user.save    @current_Time = DateTime.now    @current_Time = current_time.strftime("%Y/%m/%d %H:%M")     end  .......  end  

For the user params I sent it within the "company_attributes"

company_attributes[a_started_at => @current_Time]  

[SOLVED]

I just did users.company.started_at = DateTime.now in the create method and it worked..

How to use concurrency in a single rails test?

Posted: 19 Dec 2016 06:06 AM PST

In order to detect concurrency issues, we tried to write a few concurrent tests of the form (pseudo code): parallel_for_10_times { database.insert(name: i) }, then check if all 10 elements are correct.

Since Rails' test fixtures never really commit (in order to isolate tests from each other), DB inserts get never seen by threads other than the one creating them. Therefore, in the second step (check if the elements were created all right), they are already gone and the test fails.

So we have decided to turn fixtures off on the test (using self.use_transactional_fixtures = false as the first line of the test class) and to make sure the test DB is cleaned by putting clean statements into an ensure after the test.

Since we have done this, we randomly get very strange failures; some other tests fail due to elements created in the concurrent test only. We are pretty sure that our clean statements are working fine.

Since we are certainly not alone with this problem: What is the state-of-the-art way to write tests with multiple threads for a Rails app? Thanks in advance.

has_many :through association returns empty array on one side and filled array on the other

Posted: 19 Dec 2016 06:05 AM PST

I have a relative simple app in which a couple of categories exist and a request is made. A request is put into one or more categories.

When I add a request with one or more categories I can easily show them to the user via @request.categories.

But whenever I try to show all the requests in a single category via @category.requests I get an empty array(as inspected: #<ActiveRecord::Associations::CollectionProxy []>

Now my Rails is very rusty, so I might be doing something wrong. So here are my models:

category.rb

class Category < ActiveRecord::Base      has_many :requests, :through => :categories_requests      has_many :categories_requests  end  

request.rb

class Request < ActiveRecord::Base      has_many :categories, :through => :categories_requests      has_many :categories_requests  end  

categories_request.rb

class CategoriesRequest < ActiveRecord::Base      belongs_to :request      belongs_to :category  end  

So in short: How do I get all the requests for category 1 for example in a list in my category's show?

Activerecord: query with true does not show any result for boolean fields

Posted: 19 Dec 2016 06:30 AM PST

I have a users table with a boolean field active. I have users in the database with active: true. The problem, following query does not give any result

@users = User.where(active: true)  #this results to empty array  

But if I give 1 instead of true then I get the results.

@users = User.where(active: 1)  #this gives correct result  

I don't understand why true is not working.

Group by array and sum variable to see what is the highest

Posted: 19 Dec 2016 06:25 AM PST

Take the following array:

array = [{"filial"=>"01", "tipo_produto"=>"MR", "total"=>"1492.03"},           {"filial"=>"01", "tipo_produto"=>"MR", "total"=>"1492.03"},           {"filial"=>"01", "tipo_produto"=>"PA", "total"=>"1492.03"},           {"filial"=>"01", "tipo_produto"=>"PA", "total"=>"1492.03"}]  

I need to group by "tipo_produto" and then sum the "total" of each group to see which group has the highest total summed up. At the end I need to know which group were the highest. Here is what I have so far:

array2 = array.group_by { |d| d["tipo_produto"] }  

Which resulted in the following object:

array2 = {"MR"=>[{"filial"=>"01", "tipo_produto"=>"MR", "total"=>"1492.03"},                    {"filial"=>"01", "tipo_produto"=>"MR", "total"=>"1492.03"}],             "PA"=>[{"filial"=>"01", "tipo_produto"=>"PA", "total"=>"1492.03"},                    {"filial"=>"01", "tipo_produto"=>"PA", "total"=>"1492.03"}]}  

What are the next steps? Thank you.

table column width is not increare

Posted: 19 Dec 2016 06:12 AM PST

There is an issue to increase table column width of a particular column...

  <table id="metadata">                  <tr>        <td class="meta-head">GRN #</td>        <% if @grn.date.month >= 4 && @grn.date.month <= 12 %>          <td>            <textarea><%= "GRN"+@warehouse.shortform+"/"+(@grn.date.year.to_s.at(2..3))+"-"+(((@grn.date.year)+1).to_s.at(2..3))+"/"+(@grn.serial.to_s.rjust(5, '0')) %>            </textarea>          </td>        <% else %>          <td><textarea><%= "GRN"+@warehouse.shortform+"/"+(((@grn.date.year)-1).to_s.at(2..3))+"-"+(@grn.date.year.to_s.at(2..3))+"/"+(@grn.serial.to_s.rjust(5, '0')) %></textarea></td>        <% end %>        <td class="meta-head">Vehicle</td>        <td><textarea id="date"><%= @grn.vehicle_no  %></textarea></td>        <td rowspan="3" style="border:none; width: 200px;">          <div id="logo">            <div id="logohelp">              <input id="imageloc" type="text" size="50" value="" /><br>                  (max width: 540px, max height: 100px)            </div>           <% if @warehouse.logo != nil %>             <%= image_tag(@warehouse.logo, :alt => "logo", id: "image") %><br>           <% else %>           <% end %>         </div>       </td>     </tr>     <tr>       <td class="meta-head">GRN Date</td>       <td><textarea id="date"><%= @grn.date.strftime("%d/%m/%y")  %></textarea></td>       <td class="meta-head">Bill #</td>       <td><textarea id="date"><%= @grn.bill_no  %></textarea></td>     </tr>     <tr>       <td class="meta-head">Challan</td>       <td><textarea id="date">No. <%= @grn.challan_no  %>,   Dt.   <%= @grn.challan_date  %></textarea></td>       <td class="meta-head">Bill Date</td>       <td><textarea id="date"><%= @grn.bill_date  %></textarea></td>     </tr>     <tr>       <td class="meta-head">PO #</td>       <td><textarea id="date"><%=    @grnitems[0].purchase_order_item.purchaseorder.serial  %></textarea></td>       <td class="meta-head">Transporter</td>       <td><textarea id="date"><%= @grn.transporter  %></textarea></td>       <td rowspan="3" style="border:none; width: 200px;">       <% if @warehouse.address1 != nil %>         <h6>  <%=  @warehouse.address1 %>            <%=  @warehouse.address2 %>            <%=  @warehouse.address3 %>            <%=  @warehouse.address4 %> </h6>           <% end %>       </td>     </tr>     <tr>       <td class="meta-head">Vendor </td>       <td><textarea id="date"><%=    @grnitems[0].purchase_order_item.purchaseorder.vendor.description  %></textarea>  </td>       <td class="meta-head">LR #</td>       <td><textarea id="date"><%= @grn.lr_no  %></textarea></td>     </tr>     <tr>       <td class="meta-head">Way bill </td>       <td><textarea id="date"></textarea></td>       <td class="meta-head">LR Date</td>       <td><textarea id="date"><%= @grn.lr_date  %></textarea></td>     </tr>   </table>  

my table like enter image description here

i like to implement thelogo and address column are increase as per content. I am trying various way like

<table id="metadata" width="100%" >  <td width="100%">  

I dont know where i mistake?

How get users who like or reply a tweet?

Posted: 19 Dec 2016 04:57 AM PST

I have got a tweet's retweeters with twitter gem's method retweeters_of but this returns up to 100 users. Now, I need to get users who like or reply a tweet but I couldn't find the right way.

This is the way I get retweeters:

client = Twitter::REST::Client.new do |config|             config.consumer_key        = ENV["TWITTER_API_KEY"]             config.consumer_secret     = ENV["TWITTER_API_SECRET"]             config.access_token        = account.token             config.access_token_secret = account.secret    client.retweeters_of(post_uid)  

How to reset headers or recreate request in rspec

Posted: 19 Dec 2016 05:01 AM PST

Only first call acquire headers. Next calls with different headers give same results and seems headers doen not changed:

describe "whoami" do    context 'members' do      before {        get "/api/v1/whoami", {}, token_sign_in(user1)        p request.body # => 'user1'        get "/api/v1/whoami", {}, token_sign_in(user2)        p request.body # => 'user1'      }        it "am I user2" do         get "/api/v1/whoami", {}, token_sign_in(user2)         p request.body # => 'user1'      end    end  end  

All next results maked with same user. Possible it is not headers problem but keep-alive or some like this. (or is it bug?)

How to reset headers or connection? And how to recreate request?

Mechanize::ResponseCodeError: 405 => Net::HTTPMethodNotAllowed

Posted: 19 Dec 2016 05:14 AM PST

I am trying to fetch the data from an url using mechanize.

But it gives 405 error

url = "http://switchboard.com/business?key=habitat%20magazine&where=10001"  agent.get(url)  

Error:

Mechanize::ResponseCodeError: 405 => Net::HTTPMethodNotAllowed for http://switchboard.com/business?key=habitat%20magazine&where=10001 -- unhandled response  

I am using mechanize agent with proxy. What is the reason for getting this error? I checked the other SO questions but none have answers.

Medium authentication session across domains

Posted: 19 Dec 2016 04:48 AM PST

Recently I realised that any medium.com-backed website (say https://medium.freecodecamp.com) persist my session across domains. Even if I only visit the domain for the first time, I still see I am logged in.

Do you know what's the mechanics behind this and how can I achieve something like this with ruby on rails?

Thank you

ActiveRecord fetching records from has_many and related relationship through scopes

Posted: 19 Dec 2016 06:16 AM PST

I have two models: Customer and Order. Sometimes it happens that two Customers are actually the same customer, which is indicated by one of them having a master_id which points to another Customer record. When fetching Orders for a customer, I'd also like to fetch Orders from slave Customers (i.e. the ones that claim the Customer I'm querying from is their master Customer record).

So:

Customer1: id: 1, master_id: nil, orders: [Order1, Order2]    Customer2: id: 2, master_id: 1, orders: [Order3]  

query Customer1.all_orders should return all 3 Order objects

I know how to do this through a method - pluck ids of slave Customers, add the original customer's id to the array and then look for Orders whose customer_id is in this array:

has_many :slave_records, class_name: 'Customer', foreign_key: 'master_id'    def all_orders    order_ids = slave_records.map(&:id).push(id)    Order.where(customer_id: order_ids)  end  

But is there a way to do this using scopes and relations? It's Rails 4 (I know that Rails 5 was supposed to have an OR thing in its version of ActiveRecord).

Ruby AASM (with Rails) - how to select from different state machines?

Posted: 19 Dec 2016 04:27 AM PST

We're building a Rails app using latest AASM. We currently have ten business states and the customer tells us these should "probably" never change, but we don't want to get locked into these states forever. E.g. imagine six months from now the legal department levies a requirement to insert a "Legal Review" state into our business process.

How would we accommodate this, assuming that all our code is flexible enough to handle both the legacy machine (10 states) and the new machine (having the 11th state?) E.g. would we create a new state machine that has the 11 states and all new active record objects get the new state machine? If so, I'm not clear on how this would be done in the active record class definition. Thanks.

Why is it keep saying undefined method?

Posted: 19 Dec 2016 05:03 AM PST

Two models are created....and the associations are also mentioned in models.

first model is Item and second model is Activity.

Item model code:

class Item < ActiveRecord::Base      has_many :activities  end  

Activity Model code:

class Activity < ActiveRecord::Base      belongs_to :item  end  

i can show every item with the help of the link.....now i want to an activity to that specific item and for that purpose i have created a controller which is "Activities" and then i have written the code in it which is as follow:

Activities Model Code:

class ActivitiesController < ApplicationController      def create      @item = Item.find(params[:item_id])      @activity = @item.activities.create(activity_params)      redirect_to items_path(@item)    end      private      def activity_params        params.require(:activity).permit(:task)      end  end  

the code for the show.html.erb for the items contorller is as follow:

Show.html.erb(Items_controller) Code:

<h1>Show Goal</h1>    <p>    <strong>Goal: </strong>    <%= @item.goal %>  </p>    <p>    <strong>Description: </strong>    <%= @item.description %>  </p>    <h2>Activity</h2>  <% @items.activities.each do |activity| %>    <p>      <strong>Activity:</strong>      <%= activity.task %>    </p>    <% end %>    <h2>Add a Activity:</h2>  <%= form_for([@item, @item.activities.build]) do |f| %>    <p>      <%= f.label :Task %><br>      <%= f.text_field :task %>    </p>      <%= f.submit "Add Activity"%>    </p>  <% end %>      <%= link_to 'Edit', edit_item_path(@item) %>  <%= link_to  "Back" , items_path %>  

The error comes from this line and it says "undefined method `activities' for nil:NilClass"

<% @items.activities.each do |activity| %>  

Migration code for the "Activity" Model

Migration for Activity model Code:

class CreateActivities < ActiveRecord::Migration    def change      create_table :activities do |t|        t.string :task            t.timestamps null: false      end    end  end  

Now i can not figure out where is this error coming from "undefined method `activities' for nil:NilClass"....????????

Examples of Ruby on rails + aws congnito

Posted: 19 Dec 2016 06:11 AM PST

I am building a rails 5 app that is deployed on heroku. I want to use AWS congnito to achieve single sign on, but there are not enough example to implement it. I am using devise for authentication. Now my goal is to put my all users on AWS cognito and authenticate them from my rails App.

This is the only resource i found on AWS congnito with rails, I am looking for some example application or a link to tools or ruby API document to achieve this.

Please Help.

No comments:

Post a Comment