while filling new form this error is came. undefined method `created_by' for nil:NilClass
@user_data = UserInfo.get_user_data(@f_user_new.created_by).first
while filling new form this error is came. undefined method `created_by' for nil:NilClass
@user_data = UserInfo.get_user_data(@f_user_new.created_by).first
**I am using ruby 1.9.3 it would be helpful if i can get any gem name or method to convert the .ppt to .mp4
I am trying to cover these exceptions raised by Octokit when something undesired happens. These are some of the scenarios that needs to be covered in my spec, however I am not getting any relevant tests to refer for this: Octokit::AbuseDetected
Octokit::UnprocessableEntity
Octokit::TooManyRequests
Also I am finding no related resources for the same. This is the file that has these.
# frozen_string_literal: true
require 'asset_ingester/helpers/logging'
require 'asset_ingester/helpers/poller'
require 'octokit'
require 'colorize'
module AssetIngester
module SCM
class GithubScm
include AssetIngester::Helpers::Logging
API_ENDPOINT = 'https://github.cerner.com/api/v3/'
RESULTS_PER_PAGE = 100
DEFAULT_WAIT = 60
MAX_RETRY_ATTEMPTS = 5
def initialize
@client = Octokit::Client.new(access_token: ENV['GIT_ACCESS_TOKEN'], api_endpoint: API_ENDPOINT)
end
def search_code(search_terms)
search_results = []
search_terms.each do |search_term|
retry_on_abuse do
response = @client.search_code(search_term, per_page: RESULTS_PER_PAGE)
logger.info "Found '#{search_term}' code search results: #{response[:total_count]}"
search_results.concat(response[:items])
last_response = @client.last_response
retry_on_abuse do
while last_response.rels[:next]
last_response = last_response.rels[:next].get(query: {per_page: RESULTS_PER_PAGE})
search_results.concat(last_response.data[:items])
end
end
end
end
search_results
end
def all_organizations
logger.info 'Searching all organizations...'
search_results = []
retry_on_abuse do
response = @client.all_organizations
search_results.concat(response)
last_response = @client.last_response
retry_on_abuse do
while last_response.rels[:next]
last_response = last_response.rels[:next].get(query: {})
search_results.concat(last_response.data)
end
end
end
search_results
end
def search_repos(search_term)
search_results = []
retry_on_abuse do
response = @client.search_repositories(search_term, per_page: RESULTS_PER_PAGE)
logger.info "Found '#{search_term}' repository search results: #{response[:total_count]}"
search_results.concat(response[:items])
last_response = @client.last_response
retry_on_abuse do
while last_response.rels[:next]
last_response = last_response.rels[:next].get(query: {per_page: RESULTS_PER_PAGE})
search_results.concat(last_response.data[:items])
end
end
end
search_results
end
private
def retry_on_abuse
retry_template = 'Retrying after %d seconds. Response status: %s'
Helpers::Poller.poll(DEFAULT_WAIT, MAX_RETRY_ATTEMPTS) do
yield
rescue Octokit::AbuseDetected => e
logger.warn "Abuse detected. #{format(retry_template, DEFAULT_WAIT, e.response_headers[:status])}"
:re_poll
rescue Octokit::UnprocessableEntity => e
logger.warn "Insufficient permissions. Response status: #{e.response_headers[:status]}"
rescue Octokit::TooManyRequests => e
logger.warn "API Request Limit Reached. #{format(retry_template, DEFAULT_WAIT, e.response_headers[:status])}"
:re_poll
end
end
end
end
end
The method retry_on_abuse handles these scenarios. How do I write specs for these?
I have a haml file to generate the proposal submit page, the code is like this:
.row
%fieldset.col-md-6
=proposal.title_input(form)
=proposal.description_input(form)
%fieldset.col-md-6
.row
.col-md-3
= form.label t('.choose_tags'), { class: 'tags-label' }
.col-md-6.form-spacing
= form.hidden_field :tags, { class: 'proposal-tags' }
#tags-container.tags-container
.row
.form-submit.clearfix
.pull-left
= submit_proposal_button(proposal)
It generates a proposal submitting page which allowed the user to edit the title and description of their proposal, and the proposal's tag as well. There's a submit button on the bottom to save it.
And I want to add another input box which allowed the user to update their self-introduction as well. So, I simply added it to this file:
.row
%fieldset.col-md-6
=proposal.title_input(form)
=proposal.description_input(form)
%fieldset.col-md-6
.row
.col-md-3
= form.label t('.choose_tags'), { class: 'tags-label' }
.col-md-6.form-spacing
= form.hidden_field :tags, { class: 'proposal-tags' }
#tags-container.tags-container
// ----- the following content is what I added.-----
%fieldset.col-md-6
= simple_form_for user, url: person_path(id: user.id), html: {role: 'form'} do |f|
%h4= I18n.t('.your_profile')
.form-group
= f.input :bio, class: 'form-control', placeholder: I18n.t('.bio'),
input_html: {rows: 7}, maxlength: 1500
// ----- the above content is what I added.-----
.row
.form-submit.clearfix
.pull-left
= submit_proposal_button(proposal)
After I added it, the submit button couldn't work. Whenever I click on it, nothing happens. I'm a beginner of haml and rails, and I'm confusing about it. Any help is appreciated!
The code of submit_proposal_button is:
def submit_proposal_button (proposal)
capture_haml do
haml_tag :button,
type: 'submit',
name: 'submit',
value: proposal.id,
class: 'btn btn-primary' do
haml_concat(t('.form.submit'))
end
end
end
The following code that is inserting new rows correctly if people
isn't found. If people
is found I want it to update existing row and also the import_id
but the update isn't working. So basically if a new import contains the same data in people
I want to just update import_id
. people
has name age
.
Person.transaction do
people.flatten.each do |people|
Person.create_with({ import_id: import.id, **people }).find_or_create_by(**people)
end
end
Below is my package.json.When i run npm run rails--server.I see the errorno such file or directory webpack-manifest.json.My package.json.Please help me know where I am going wrong.
{
"name": "logging_response_engine-client",
"private": true,
"browserslist": [
"extends browserslist-config-terra"
],
"scripts": {
"build:test": "webpack --config node_modules/orion-toolkit-js/lib/conf/react-on-rails/webpack/engine/webpack.config.js -p",
"build:production": "NODE_ENV=production webpack --config node_modules/orion-toolkit-js/lib/conf/react-on-rails/webpack/engine/webpack.config.js -p",
"build:development": "webpack --config node_modules/orion-toolkit-js/lib/conf/react-on-rails/webpack/engine/webpack.config.js"
},
"entryPointDependencies": [
"logging-response-component"
],
"dependencies": {
"logging-response-component": "git://github.cerner.com/GS077478/logging-response- component.git#master",
"orion-application": "^1.1.0"
},
"devDependencies": {
"@babel/cli": "^7.4.4",
"@babel/core": "^7.4.4",
"babel-loader": "^6.3.2",
"@babel/plugin-proposal-object-rest-spread": "^7.4.4",
"@babel/plugin-transform-object-assign": "^7.2.0",
"@babel/plugin-transform-regenerator": "^7.4.5",
"@babel/preset-env": "^7.4.5",
"@babel/preset-react": "^7.0.0",
"browserslist-config-terra": "^1.0.0",
"core-js": "^3.1.3",
"raf": "^3.4.1",
"orion-toolkit-js": "^4.0.0",
"react": "^16.8.5",
"react-dom": "^16.8.5",
"react-intl": "^2.4.0",
"react-on-rails": "7.0.4",
"regenerator-runtime": "^0.13.2",
"terra-toolkit": "^5.0.1",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.3.1",
"orion-webpack-plugins": "^1.0.0",
"webpack-manifest-plugin": "^2.2.0"
}
}
what is the idea behind creating a new instance of the method inside class << self construct? I understand methods are put under class << self block to make it class methods but what it means to creating a new instance of the method itself?
class foo
class << self
def bar(param)
new.bar(some_param)
end
end
end
i want to search for users ignoring the accents i tried to use I18n.transliterate and it worked, but i don't know how to use it in search results
def list
page = get_pagination_params[:page] || 1
results = User.page(page).per(Settings.pagination.per_page)
search_params = get_search_params()
@text = search_params[:text] if search_params[:text].present?
results = results.where('name ILIKE ?', "%#{search_params[:text]}%") if @text.present? && @text != ''
#@text = I18n.transliterate(@text) if search_params[:text].present?
@role = search_params[:role] if search_params[:role].present?
results = @role.present? ? results.where(role: @role) : results.where.not(role: [:guest, :quiz_candidate, :client])
@users = results
end
I'm working in a legacy rails application, I'm trying to clean up some CSRF vulnerabilities. In playing around with this I've found that if I open the page (localhost development environment) in question up in the browser, and remove the hidden CSRF field from the form I can still successfully submit the form. The only indication that something is amiss is a warning in the logs: WARNING: Can't verify CSRF token authenticity
.
Is this standard behaviour? Normally (at least in Rails 4+) if you try to submit a protected form without the accompanying token ApplicationController will through an error. Should my app be crashing when I remove the CSRF field? Any ideas on why it might not be?
I'm having trouble with the scope "(:locale)"
and mount SimpleDiscussion::Engine => "/forum"
is giving me this error: ActionController::UrlGenerationError in SimpleDiscussion::ForumThreads#index
And this route not matches: No route matches {:action=>"index", :controller=>"simple_discussion/forum_threads", :locale=>:es}
This is part of my routes
Rails.application.routes.draw do
scope "(:locale)", locale: /en|es/ do
mount SimpleDiscussion::Engine => "/forum"
...
end
This is the view that gave me the error
<% if I18n.locale == :es %>
<%= link_to t('home.navbar.english'), url_for( locale: :en ), class: "nav-link dropdown-toggle", method: :get %>
<% elsif I18n.locale == :en %>
<%= link_to t('home.navbar.spanish'), url_for( locale: :es ), class: "nav-link dropdown-toggle", method: :get %>
<% end %>
Is there a way to config locales and mounted engines? Thanks!
Need to pass on filtered data without changing the name of the field in response using serializable hash. A User entity which is related to Class. User uses serializable_hash as:
def serializable_hash(options={})
super(:only => [:id, :email, :phone, :first_name, :last_name],
:include => [:classes ]
end
Where I want to filter classes based on active status. Like :methods => [:types , :active_classes]) but this particular field to be shown as classes not active_classes in the response like:
{"id": ...,
"email": ....,
"classes": []
}
I've got three instance variables:
@book, @recent_books, @popular_books
@books contains 1 currently viewed record, @recent_books contains 10 records, and @popular_books contains 10 records
I want to assign a variable to them and put them into a hash together, so in my controller I've got:
@book_list = [@book, @recent_books, @popular_books]
Now in my view I want to iterate over each of them and display the information for each:
@book_list.each_with_index do |(book_list), index|
book_list.title,
book_list.author,
index + 1,
etc
The issue I've got is this only iterates over three records instead of 21. However if I check @book_list I can see all 21 records, but @book_list.count only lists three. I understand why this is happening, but not how to fix it so that it iterates through all 21 records.
Getting the above mentioned error when try to start the server. I am using rails 4.2.2 with ruby 2.2.2
This is my code -
def self.constant_discovery(file_name, pattern)
matches = File.open(file_name).read.scan(pattern).uniq.flatten.compact
matches_found = matches.map {|key| key.split(',')[0].scan(/^[A-Z]+(?:_[A-Z]+)*$/)}.flatten
search_pattern = /([A-Z]+_)*[A-Z]+ = '.+'/
File.open(file_name) do |f|
lines = f.find_all {|line| line =~ search_pattern }
lines.each do |line|
if line.include?('=')
print line unless line.empty?
required_output = matches_found & line
end
line
end
end
matches
end
By the above code I'm getting matches_found values like below, ["TEST_ONE", "TEST_TWO", "TEST_THREE","TEST_FOUR"]
Where as, line is producing output like this,
TEST_ONE = 'testone'
TEST_TWO = 'testtwo'
TEST_THREE = 'testthree'
TEST_FOUR = 'testfour'
KEY_AS_PRIMARY = 'primary'
In the require_output I need to get the common constant values from matches_found and line and from that common constant value I have to return the value which the common constant assigned to. While trying this I'm facing issue when comparing matches_found and line and getting error like "failed with error no implicit conversion of String into Array "
By this I understood that I have to convert values of line to an array and then should compare it with matches_found, after this I'll be getting common constant from both the arrays in required_output and later I can get the value which is assigned to those common constants as return values of that method. As I'm very new to ruby can someone please help me with it?
I have following methods,
Model/Summary.cs
def show_summary
device_lastest_reading = lastest_reading
end
Model/Reading.cs
def lastest_reading
select_readings(start_date, last_date)
end
The lastest_reading
method get the values from a hardware. I have created a DummyReading.rb
for RSPEC and placed the lastest_reading
method as like below,
DummyReading.rb
def lastest_reading
{
:a=>13,
:b=>"7666",
:c=>6729690,
}
end
here is what i tried,
it "should return summary data" do
allow(DummyReading.lastest_reading).to receive(Model.show_summary).and_return({})
end
I an getting error "undefined method
to_sym' for {}:Hash`"
In rspec how to mock/stub this device_lastest_reading variable.
Thank you.
I try to build my site with as much as possible testing, but since I integrated i18n many of my tests failed. Of course it is because of my standard locales. But how do I ignore the locales while testing? My about link looks like: /about?locale=en and the test:
test "layout links" do
get root_path
assert_template 'static_pages/home'
assert_select "a[href=?]", root_path, count: 1
assert_select "a[href=?]", helf_path
assert_select "a[href=?]", about_path
assert_select "a[href=?]", contact_path
end
I am currently developing a project for space bookings. Its an API project. I have done till Booking API. But want to check availability check and validations for booking. How to write logic code for checking availability of the space and to do validations on weather the space is available or not. The spaces I am using in this project is meeting rooms, private space, and desks
This is my space creation JSON
{
"space": {
"name": "Star Bucks",
"email": "stabucks@mail.com",
"website" : "www.starbucks.com",
"phone" : "7907653366",
"amenities_attributes": [
{
"name": "wifi",
"available": true
},
{
"name": "ac",
"available": true
}
],
"meeting_rooms_attributes": [
{
"count": 5,
"capacity": 6
}
],
"private_offices_attributes": [
{
"count": 2,
"capacity": 6
}
],
"desks_attributes": [
{
"count": 12,
"desk_type": "open_desk"
}
],
"operating_hours_attributes": [
{
"day": "Mon-Fri",
"slot": "10:00-5:00"
}
]
}
}
This is my Space booking request JSON
{
"booking": {
"space_id": 17,
"booking_items_attributes": [
{
"entity_type": "PrivateOffice",
"entity_id": 20,
"count": 1
},
{
"entity_type": "Desk",
"entity_id": 20,
"count": 2
}
],
"booking_dates_attributes": [
{
"from_date": "2020-03-18",
"to_date": "2020-03-18",
"from_time": "2020-03-18 10:00:00 ",
"to_time": "2020-03-18 14:00:00 "
}]
}
}
Booking Controller
class Api::V1::BookingsController < ApiController
before_action :fetch_space, only: [:show]
def index
bookings = Booking.all
render_collection(bookings, { name: 'bookings' }, each_serializer: BookingItemSerializer)
end
def create
if booking = current_user.bookings.create(booking_params)
render_object(booking, { name: 'booking' }, { serializer: BookingSerializer })
else
render_error(booking.errors.full_messages)
end
end
private
def booking_params
params.require(:booking).permit(:space_id,
booking_items_attributes: [:id, :entity_type, :entity_id, :count],
booking_dates_attributes: [:id, :from_date, :to_date, :from_time, :to_time])
end
end
Booking Serializer
class BookingSerializer < ActiveModel::Serializer
attributes :id, :user_id, :space_id, :status, :booked
# has_many :booking_items, serializer: BookingItemSerializer
def booked
object.booking_items.entity_type.sum(:count)
end
end
Booking Item Serializer
class BookingItemSerializer < ActiveModel::Serializer
attributes :id, :availabitity
belongs_to :booking, serializer: BookingItemSerializer
# def availabitity
# availabitity = object.meeting.sum(:count) - booked
# end
end
I wanted to use an API with my existing rails app without using any gem so that I can get the basic concept. How can that be done? Thanks for the help.
In a controller I have an update
method which creates a record (call it book
), associates it to an existing record (call it author
) and saves it.
Book
belongs to one Author
add_author_to_book_controller.rb
def update
@author = App::Models::Author.new(params)
@book = App::Models::Book.where(id: params[:book_id]).first
@book.author = @author
@book.save!
# this works fine...
# puts @book.author.inspect
render json: { status: :ok }
end
add_author_to_book_controller_spec.rb
describe App::AddAuthorToBookController do
describe '#update' do
# this is a contrived example, there is more setup regarding creating the "book" properly...
let(:name) { 'foobar' }
let(:action) { xhr :put, :update, params }
let(:params) { { first_name: name } }
subject { book }
before { action }
it { expect(response.status).to eq 200 }
it 'should save the author to the book' do
# why is author nil here?
# puts book.author.inspect
expect(book.author.first_name).to eq name
end
end
end
I tried book.reload
in the test but that didn't work. I'm new to rails, is there some conventional way of testing an associated record in a controller test?
I want to use DynamoDb and want to use it with rails. I have found that the dynamoid gem seems to be the most used Dynamo ORM library for ruby.
I understand that the Dynamoid documentation uses hash/range key terminology (old terminology)
However I am running into a problem where I want to have compound attributes in my partition key.
For a simple example say that I have a Products
table that has an product_id
and a title
.
The primary partition key for this item will just be the product_id
Now say that I have another table Orders
. I want the primary partition key to be: orders##
. I.e I want to have compound attributes in the primary partition key as outlined in this document: https://aws.amazon.com/blogs/database/choosing-the-right-dynamodb-partition-key/ with the attributes seperated by a hash.
I found this post https://github.com/Dynamoid/Dynamoid/issues/265 that outlines how to use compound attributes with range
but this only takes care of sort-keys.
I have tried things like:
class Order
include Dynamoid::Document
key: "Order##{:product_id.to_s}##{:datetime.to_s}"
field :product_id
field :datetime
end
But this of course does not work and causes issues when initializing the table.
Is this possible with dynamoid? Such primary key naming seems to be common among aws documentation? I have not found this in the documentation.
thanks
I upgraded to Ruby 2.4 and started getting this error:
ArgumentError in ConfessionsController#index
key must be 32 bytes
# cipher = new_cipher
cipher.encrypt
cipher.key = @secret
# Rely on OpenSSL for the initialization vector
iv = cipher.random_iv
I read the whole internet about it, and people posted about changing the encryption keys. But I don't even have such a files, so I have no idea what to change and how to fix this. Could someone please help?
Can we interact with two different languages by using an interprocess communication mechanism in Linux? Mainly C or C++ and Ruby. I just want to call Class methods and library of C or C++ from Ruby. Is it possible to call it?
Once we design the card in the studio page after login we are facing this error please help me out. I have a very simple controller A NoMethodError occurred in studio#create_flatz, Thank you in advance
ruby version 1.9.3
rails 3.2.13
class StudioController < ApplicationController
before_filter :current_or_guest_user, :only =>[:create_flatz]
def splash_page
end
def index
end
def create_flatz
@cart=current_cart
@CartCount = @cart.total_quantity.to_s
end
def upload_art
end
def current_cart
@cart ||= Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
@cart
end
end
A pneumonia outbreak ... 1. Infected people have an incubation period of two days. They will not be contagious during the incubation period and will only infect other people after they become ill. 2. Infected people can be transmitted to 2 people who have not been infected every day. 3. As long as you are infected, you will not be cured! Suppose there is only one original person at the beginning. How many people will be infected after 20 days?
def infected(days)
end
puts infected(20)
I am trying to find if there is mango/cc:
in my data
and if its there update its value to new_version
, if its not there add mango/cc:#{new_version}
My data
{"product"=>"fruit", "id"=>"alpha", "details"=>{"SS"=>["mango/aa:50", "mango/cc:287_457_51.0.0"]}}
Code:
new_version = "287_457_53.0.0"
var1 = data['details']['SS'].select{|x| x.start_with?('mango/cc:')}
if var1.empty?
data['details'] << "mango/cc:#{new_version}"
else
data['details'].delete(var1)
data['details'] << "mango/cc:#{new_version}"
puts data
Current Output:
`[]': no implicit conversion of String into Integer (TypeError)
Expected Output:
{"product"=>"fruit", "id"=>"alpha", "details"=>{"SS"=>["mango/aa:50", "mango/cc:287_457_53.0.0"]}}
Only nil and false are indeed the only two values, that evaluate to false in Ruby. Am I right? Also how about "" double qoutes with no value, is this same as NIL so the statement will be false? Correct me If Im wrong
I have a unique question and looking for guidance on where to start looking. I'm new to Rails and Ruby.
I'm looking to take a spreadsheet of information, in this example, it's going to be a list of locations, like cities across the US. And then take that spreadsheet of information and have my rails application create pages for each one of the cities.
My current setup is much like a blog, so I have Posts has a model. Your basic Rails scaffold of posts. Directionally speaking, how would I start looking into methods to write and run a script in production that would automate the creation of Posts based on the spreadsheet list of cities?
everybody... For a couple of days I have encountered a problem in my application and that is giving me a lot to think about: I have a data table called "Devices" that contains a reference to "Users", in my data table I am bringing back the "user_id" but I want to take that data in the backend and show the "username" in the frontend. How can I get the expected result? I would greatly appreciate with any help you can give me
in the "user" column the "user_id" is hosted columns
in my index.html.haml:
.table__wrapper
= form_tag edit_multiple_devices_path, method: :get do
%table{:role => 'datatable'}
%thead
%tr
%th
%th.abbr{:title => "aidi"} Id
%th.abbr{:title => "imei"} Imei
%th.abbr{:title => "brand"} Marca
%th.abbr{:title => "model"} Modelo
%th.abbr{:title => "prov"} Proovedor
%th.abbr{:title => "fac"} Factura
%th.abbr{:title => "din"} Entrada
%th.abbr{:title => "sim"} Sim
%th.abbr{:title => "iccid"} Iccid
%th.abbr{:title => "status"} Status
%th.abbr{:title => "user_id"} Usuario
%th.abbr{:title => "client"} Cliente
%th.abbr{:title => "dout"} Salida
%th.abbr{:title => :use} Usado
%th.abbr{:title => :old} Reutilizado
%tbody
- @devices.each do |device|
%tr
%td= check_box_tag "device_ids[]", device.id
%td= device.aidi
%td= device.imei
%td= device.brand
%td= device.model
%td= device.prov
%td= device.fac
%td= device.din
%td= device.sim
%td= device.iccid
%td= device.status
%td= device.user_id
%td= device.client
%td= device.dout
%td= device.use
%td= device.old
= submit_tag "Editar", class: "button is-primary is-rounded"
in my device.rb
class Device < ApplicationRecord
belongs_to :user
attr_accessible :aidi, :imei, :brand, :model, :prov, :fac, :din, :sim, :iccid, :status, :user_id, :client, :dout, :use, :old
end
in my user.rb
class User < ApplicationRecord
has_many :devices
end
thanks for the knowledge
There are similar questions like this, this, this, and this, but they don't address the problem.
We have a locally stored image that is rendered in the development environment.
In production, however, the image doesn't render. Accessing the image URL from the browser gets redirected to the 404 page because the image isn't found for some reason. Other images in the same directory are rendered without issue.
Details: * Image 1 URL: https://test.com/designs/thumbnails/foo/bar1.jpg * Image 2 URL: https://test.com/designs/thumbnails/foo/bar2.jpg
Entering both image URLs directly into the browser yields different results. Image 1 will render, but image 2 won't. Image 2 redirects to the 404 page.
This isn't a caching issue; rendering in incognito fails.
Both images exist in the directory.
This seems to occur for new images, though the pattern isn't clear (i.e., some new images render but not all do).
We use Rails 3.2 and Cloudflare.