Facing issue NoMethodError (undefined method `include' for "56":String): - ruby-on-rails

I am facing issue while writing this code
def sim_state
sim_employees = SimEmployee.find(params[:id].include(:employees))
respond_to do |format|
format.js {
render :layout => false,
:locals => {
:sim_employees => sim_employee
}
}
end
end
and in my sim_states.js.erb
$('#simState').text('<%= sim_employee.employees.app_state%>');
So it gives me this error
NoMethodError (undefined method `include' for "56":String):
when i use it with includes then it gives
undefined method `includes'
Please guide me how to solve this.

The reason is simple
params[:id]
is return you a String value which is "56" and includes works with ActiveRecord::Relation and not string. So you are not able to fire the query that ways.
SimEmployee.find(params[:id])
This will return again a result and not relation. Try using
SimEmployee.where(id: params[:id]).includes(:employees).first
This should help you.
PS : Using includes for one record is same as firing two independent queries i.e.
#sim_employee = SimEmployee.find(params[:id])
#emplyess = #sim_employee.employees

There is a simple solution for this:
SimEmployee.includes(:employees).find params[:id]

SimEmployee.find(params[:id].include(:employees))
This line is causing the issue, you are calling include(:employees) on params[:id] which would be a number.
And you can't actually do .find(params[:id].include(:employees) because find method returns an instance of Model class, in this case, an instance of SimEmployee class, and you can't run method include on it.
Edit:
SimEmployee.includes(:employees).where()
You can pass a hash in where(). This works if your SimEmployee model has has_many relation to Employee model.

Related

rails 5 ForbiddenAttributesError on bulk operations

i try to bulk operation in my rails controller this is my script
def update_by_user
user_skill_selected = UserSkillSelected.create(params[:user_skill_selected][:users])
# check through array if all is valid
if user_skill_selected.all? {|item| item.valid?}
render json: {json_status: save_success}
else
render json: {json_status: save_failed}
end
end
and this is my user_skill_selected_params
def user_skill_selected_params
params.require(:user_skill_selected).permit(:user_id, :subskill_id, :skill_id, :users => [])
end
unfortunately i get an error in my log, the log said
"exception": "#<ActiveModel::ForbiddenAttributesError:ActiveModel::ForbiddenAttributesError>",
after that i try to bulk operations from rails console with using create method with the array value and its work
can anyone solve this... :(
sorry for the bad english
This can be confusing. Your code is passing in params[:user_skill_selected][:users] to the model create method, instead of your user_skill_selected_params strong parameters, which is why you're seeing that error.
Change this line:
user_skill_selected = UserSkillSelected.create(params[:user_skill_selected][:users])
To this:
user_skill_selected = UserSkillSelected.create(user_skill_selected_params)
And it should eliminate this error.

Rails: first_or_create not working

Very strange issue with first_or_create. Consider the following method:
def self.store(session)
shop = self.first_or_create(shopify_domain: session.url, shopify_token: session.token)
binding.pry
shop.save!
shop.shopify_domain
end
When I pry into this method, I can call session.url to get domain2.myshopify.com and session.token to get 22222
But when I call shop, I get a shop where shopify_domain: domain1.myshopify.com and shopify_token: 11111.
Any idea why this would happen? It seems bizarre.
shop = self.where(shopify_domain: session.url, shopify_token: session.token).first_or_create(shopify_domain: session.url, shopify_token: session.token)
You are just getting the first one in general. Like calling .all.first

Undefined method 'id' for Class, but the console loads fine

I can access the shopping_list_products loaded in this API call from the console with no error.
I get a 500 on the API, however:
ActionView::Template::Error (undefined method `id' for #<Class:0x007f6cca7e1dd0>):
2015-01-26T23:51:07.608697+00:00 app[web.1]: 1: collection :#shopping_list_products
2015-01-26T23:51:07.608699+00:00 app[web.1]: 2: extends 'api/v1/shopping_list_products/_show'
index.json.rabl:
collection :#shopping_list_products
extends 'api/v1/shopping_list_products/_show'
show.json.rabl:
object :#shopping_list_product
extends 'api/v1/shopping_list_products/_show'
_show.json.rabl:
object :shopping_list_product
attribute(:id, :if => lambda { |m| m.id })
attributes :shopping_list_retailer_id, :product_id, ...
... more attributes
child :product, partial: 'api/v1/products/_show'
child :product_category, partial: 'api/v1/product_categories/_show'
node(:url) do |shopping_list_product|
api_v1_schedule_requisition_plan_shopping_list_shopping_list_retailer_shopping_list_product_path(#schedule, #shopping_list_retailer, shopping_list_product, format: :json)
end
EDIT: I removed the id attribute and then ran into the next error, "undefined method shopping_list_retailer_id for Class:". Why is this happening?
EDIT: Found out it's my code called from the controller.. if I return
#shopping_list_retailer.shopping_list_products
it works fine.
But I do this instead:
api :GET, '/schedule/:schedule_id/requisition_plan/shopping_list/shopping_list_retailers/:shopping_list_retailer_id/shopping_list_products', 'List all shopping list products for Shopping List for Requisition Plans for Schedule in the database'
param :query, String, desc: "Scoped_search style query string"
def index
#shopping_list_products = ShoppingListProductsIndexQuery.new(#shopping_list_retailer, params[:query]).shopping_list_products
end
class ShoppingListProductsIndexQuery
attr_reader :shopping_list_retailer, :query
def initialize(shopping_list_retailer, query)
#shopping_list_retailer = shopping_list_retailer
#query = query
end
def shopping_list_products
#shopping_list_retailer.shopping_list_products.ordered_by_product_category_type_and_product_category_name_and_product_name.search_for(query)
end
end
Still confused why undefined method id for Class is hit in the rabl view.
Your error message (undefined method 'id' for #<Class:0x007f6cca7e1dd0>) is saying the undefined method is on an instance of Class instead of an instance of ShoppingListProduct (or whatever your actual class name is).
This means the wrong thing is being rendered.
Probably because you are using:
object :#shopping_list_products
# and
object :#shopping_list_product
Instead of:
object #shopping_list_products
# and
object #shopping_list_product
Remove the :s.
Also, in your _show.json.rabl file, you really don't need
object :shopping_list_product
as this is ignored when the RABL template is being used as a partial (https://github.com/nesquena/rabl/wiki/Reusing-templates)

undefined method `coordinates' for nil:NilClass

I'm new to Rails and trying to figure out an issue with a Rails 2.3.14 site. The problem is this store locator i'm trying to fix keeps returning
undefined method `coordinates' for nil:NilClass
when it can't find a store within the distance parameters. If it finds one then it works ok.
Here is the current code i'm trying to work with in my controller
#map = GMap.new("locations-gmap-div", "locationsGMap")
#map.control_init(:large_map => true, :map_type => true)
#mapp.center_zoom_init(#locations.first.coordinates, 8)
This is what I tried to do with my code. I'm still very new to Rails so I apologize if i'm going way off field here.
#map = GMap.new("locations-gmap-div", "locationsGMap")
#map.control_init(:large_map => true, :map_type => true)
if #map.center_zoom_init(#locations.first.coordinates,8).nil?
flash[:error] = 'Sorry, we could not find any stores matching that criteria.'
redirect_to store_locator_path
else
#map.center_zoom_init(#locations.first.coordinates,8)
end
Any help would be greatly appriciated.
Its failing because the #locations are empty.
#locations will return []
#locations.first will return nil
nil.coordinates raises undefined method `coordinates' for nil:NilClass
if #locations.empty?
flash[:error] = 'Sorry, we could not find any stores matching that criteria.'
redirect_to store_locator_path
else
#map = GMap.new("locations-gmap-div", "locationsGMap")
#map.control_init(:large_map => true, :map_type => true)
#map.center_zoom_init(#locations.first.coordinates,8)
end
You haven't initialized #locations.first. The program seems to be trying to access the coordinates of something that doesn't exist (hence why the exception is on nil:NilClass).

Search in child model in Ruby on Rails

A company model has many tag and has a country_id field. I would like to find:
all companies, located in a certain county
all companies, located in a certain county and has a certain tag if params[:tag] is present.
The first query is pretty easy
Company.where(:country_id => params[:country_id])
As for second one, I tried some queries and nothing worked
companies = Company.where(:country_id => params[:country_id])
companies = Company.tags.where(:name=> params[:tag])
undefined method `tags' for #<Class:0x000000055dfb60>
If I put
Company.tags.where(:name=> params[:tag])
then the error is the same
undefined method `tags' for #<Class:0x000000055dfb60>
In Rails console a command Company.first.tags receives all tags as it does.
UPDATE: this works
Company.joins(:tags).where("tags.name = ?", query_hash[:tag])
But I don't understand yet how to do something like this
my_conditions = get_search_conditions
if query_hash[:tag].present?
companies = Company.all(:conditions => my_conditions).joins(:tags).where("tags.name = ?", query_hash[:tag])
else
companies = Company.all(:conditions => conditions)
end
The error is
undefined method `all' for #<Array:0x007fbec8063e00>
The error is undefined method all for #<Array:0x007fbec8063e00>
It should work if you replace Company.all with Company.where
check if this works - Company.joins(:tags).where("tags.name",params[:tag])

Resources