How a set a "search" value to a variable in a controller - ruby-on-rails

I had a value that is inserted in a input at index and led me to a show page.
But, when I insert and submit, I gain a Blank Page! However, if I type in the URL the path to the show item, it appears!
Print from the input on client side:
https://imgur.com/a/ZSnacmM
I tried and get the following result with biding pry
https://imgur.com/a/d3H9VAi
The "entrega" really comes with the input that is the cient_number, but #entrega does'nt
So, When goes to if, all the values are nil. I really don't understand
I've tried the following code at Controller:
def sac_index
#binding.pry
#objectives = DeliveryObjective.all
#search = params["search"]
if #search.present?
#entrega = #search["client_number"]
#objectives = DeliveryObjective.where(client_number: #entrega)
end
##search_uol = DeliveryObjective.where(client_number: params[:id])
end
def sac_show
##delivery_objective = DeliveryObjective.where(client_number: #search)
#delivery_objective = DeliveryObjective.where(client_number: params[:id])
binding.pry
end
When I input the client_number, I want to be rendered to the show page from the item.

Based in an earlier response, I resolved the conflict, changing the Controller:
def index
#objectives = DeliveryObjective.all
#search = params["search"]
if #search.present?
#entrega = #search["client_number"]
#objective = DeliveryObjective.where(client_number: #entrega)
end
end
def show
#search = params["search"]
if #search.present?
#entrega = #search["client_number"]
#delivery_objective = DeliveryObjective.where(client_number: #entrega)
end
end
It's a little bit dirty, but can help someone.

Related

Unable to convert unpermitted parameters to hash

I've followed multiple stack overflow posts regarding this same issue, but I don't think I have the rails proficiency to know how to apply these fixes to my code.
Been following an old railscast show: http://railscasts.com/episodes/217-multistep-forms
And I'm aware that the issue is something to do with permitting objects/hashes but I just don't understand it all.
The error I'm getting is from this line of code in my controller:
session[:zerch_params].deep_merge!(params[:zerch]) if params[:zerch]
Controller
class ZerchesController < InheritedResources::Base
def index
#zerches = Zerch.all
end
def show
#zerch = Zerch.find(params[:id])
end
def new
session[:zerch_params] ||= {}
#zerch = Zerch.new(session[:zerch_params])
#zerch.current_step = session[:zerch_step]
end
def create
session[:zerch_params].deep_merge!(params[:zerch]) if params[:zerch]
#zerch = Zerch.new(session[:zerch_params])
#zerch.current_step = session[:zerch_step]
if #zerch.valid?
if params[:back_button]
#zerch.previous_step
elsif #zerch.last_step?
#zerch.save if #zerch.all_valid?
else
#zerch.next_step
end
session[:zerch_step] = #zerch.current_step
end
if #zerch.new_record?
render "new"
else
session[:zerch_step] = session[:zerch_params] = nil
flash[:notice] = "zerch complete!"
redirect_to #zerch
end
end
private
def zerch_params
params.require(:zerch).permit(:location, :category, :price)
end
end
So I was able to solve this from the model and in the controller:
I still had
attr_accessor
while also having params in private. I removed this, and also in the controller I changed the line of code from this:
session[:zerch_params].deep_merge!(params[:zerch]) if params[:zerch]
to this:
session[:zerch_params].deep_merge!(params.permit![:zerch]) if params[:zerch]

undefined method `<<' for #<Answer::ActiveRecord_Relation:0x007fada31c7430>

Hi I create a controller Game to display a Q/A game
And I am blocked with <<, here is the code
def play
lvlup(lvl)
if lvl == 1
set_questions
else
get_questions
end
#answers = Answer.where.not(id: question.answer_id).limit(2).order("RANDOM()")
#answer ||= []
#answers << question.answer
#answers = #answers.shuffle
render 'play'
end
I create an array and I put the related answer in the global answers I want to display 4 Max.
Why does the undefined is here?
Here is the total code
class GamesController < ApplicationController
attr_accessor :lvl
def welcome
end
def congrat
end
def play
lvlup(lvl)
if lvl == 1
set_questions
else
get_questions
end
#answers = Answer.where.not(id: question.answer_id).limit(2).order("RANDOM()")
#answer ||= []
#answers << question.answer
#answers = #answers.shuffle
render 'play'
end
def loose
#question = Question.find(params[:question])
flash.now[:alert] = "Miss..."
render 'loose'
end
def check
#lvl = params[:lvl].to_i
answer_id = params[:id].to_i
question = Question.find(params[:question])
if #lvl == lvlmax
render action: 'congrat' and return
elsif answer_id == question.answer_id
flash.now[:notice] = "Well done !"
play
else answer_id != question.answer_id
loose
end
end
private
def lvlup(value)
#lvl = 1 + value.to_i
end
def lvlmax
#lvlmax = Question.all.count
end
def set_questions
#questionsids = []
Question.all.shuffle.each do |d|
#questionsids << d.id
end
cookies[:questions] = #questionsids
end
def get_questions
#questions = cookies[:questions].split('&')
end
def questions
#questions = cookies[:questions]
end
def question
#question = Question.find(questions[lvl])
end
end
Thank you for your help.
You are trying to append to the #answers result - this is an ActiveRecord relation, you cannot append data to that array.
Add .to_a in the end of your line where you set #answers to allow you to append to the array.
#answers = Answer.where.not(id: question.answer_id).limit(2).order("RANDOM()").to_a
mtrolle's answer might be correct, but I have my doubts as to why ActiveRecord::Relation was not returned as Array by default. (Also as mentioned by BroiStatse in his comment.)
I too noticed the same problem with my local setup however it was attributed to another issue all together. I am sharing this here in case you too happen to use MySQL.
Answer.where.not(id: question.answer_id).limit(2).order("RANDOM()")
returns an ActiveRecord::Relation object. And it translates to following SQL:
SELECT `answers`.* FROM `answers` WHERE (id != ID) ORDER BY RANDOM() LIMIT 2
When I try running the same in MySQL, I get:
ERROR 1305 (42000): FUNCTION database.RANDOM does not exist
Apparently MySQL does not have RANDOM() function, instead it uses RAND().
Converting ActiveRecord query accordingly returned correct Array to me:
Answer.where.not(id: question.answer_id).limit(2).order("RAND()")

NoMethodError undefined method

Working on final class project. I need to calculate the GPA of my major credits and non major credits separately for a transcript page. When I run this code below as a controller it works fine and show my total credit hours for major and non major but when I put this code
#GPA_for_major = (course.credits * course.grade.scale) / course.credits
in the If statement I get NoMethodError in TransController#transcript
undefined method 'credits' for # Course::ActiveRecord_Relation:0x00000007b99798>
class Transcript
def initialize (course_array)
#course = course_array
#total_non_major_credits = 0
#total_major_credits = 0
#GPA_for_major = 0
#GPA_for_non_major = 0
for item in #course
if item.is_for_major
#total_major_credits = #total_major_credits + item.credits
else
#total_non_major_credits = #total_non_major_credits + item.credits
end
end
end
def course
#course
end
def total_non_major_credits
#total_non_major_credits
end
def total_major_credits
#total_major_credits
end
def GPA_for_major
#GPA_for_major
end
def GPA_for_non_major
#GPA_for_non_major
end
end
This is the Controller for my transcript page
class TransController < ApplicationController
def transcript
#courses = Course.all
#transcript =Transcript.new(#courses)
end
end
I'm not sure what else to include because this is my first post but any help will be awesome! Thanks!
#course appears to refer to an array of courses and the if statement is within a loop that iterates over the items setting a local variable item for each course. Given that, you should use item instead of course:
#GPA_for_major = (item.credits * item.grade.scale) / item.credits

How to merge two objects in Ruby on Rails

I'm trying to retrieve from the database two contents: the first one with the field source equal to "imported" (which means that we import it from the excel spreadsheet), and the second one with source != imported (we create it from scratch). Attached is my code:
def index
add_breadcrumb 'Projects', projects_path
add_breadcrumb #project.name, #project
add_breadcrumb "List #{#category.display_name} Content", project_category_contents_path(#project, #category)
#contents_imported = Content.of_project(#project).with_category(#category).imported.order('contents.created_at asc')
#contents_not_imported = Content.of_project(#project).with_category(#category).not_imported.order('contents.created_at desc')
#page = params[:page]
#contents = #contents_not_imported << #contents_imported
#q = #contents.search(params[:q])
#content = #q.result(distinct: true).page(#page).per(20)
end
#contents_imported = Content.of_project(#project).with_category(#category).imported.order('contents.created_at asc')
#contents_not_imported = Content.of_project(#project).with_category(#category).not_imported.order('contents.created_at desc')
And I want to combine the two results before showing it:
#contents = #contents_not_imported << #contents_imported
but it didn't work. How can I do that?
If both of them are arrays and are having same type of objects you can do Result = Arr1 | Arr1
That also removes the duplicates. Its like boolean UNION. In your case #contents = #contents_not_imported | #contents_imported
The problem is that you want to concatenate results, but you also want to continue treating the combined results as an ActiveRelation (call .search on it). Here's a simpler approach that avoids the need for concatenation in the first place. You will need a more complex ORDER BY clause to accomplish this, however:
#page = params[:page]
#contents = Content.of_project(#project).with_category(#category).
order('CASE WHEN source <> "imported" THEN contents.created_at END desc, CASE WHEN source = "imported" THEN contents.created_at END asc')
#q = #contents.search(params[:q])
Concatenating the arrays is done with the plus sign
You are getting undefined method search for Array because, concatenating will return you an array. And you can't call search method on that Array
EDIT
def index
add_breadcrumb 'Projects', projects_path
add_breadcrumb #project.name, #project
add_breadcrumb "List #{#category.display_name} Content", project_category_contents_path(#project, #category)
contents_imported_ids = Content.of_project(#project).with_category(#category).imported.order('contents.created_at asc').map(&:id)
contents_not_imported_ids = Content.of_project(#project).with_category(#category).not_imported.order('contents.created_at desc').map(&:id)
#page = params[:page]
contents_ids = contents_imported_ids + contents_not_imported_ids
contents = Content.where(content_ids)
#contents = content_ids.collect{|id| contents.detect{|c| c.id == id}}
#q = #contents.search(params[:q])
#content = #q.result(distinct: true).page(#page).per(20)
end
Just create a new Relation with the conditions of imported or not imported, after that, order all the records (if order is important to #contents and #content):
def index
add_breadcrumb 'Projects', projects_path
add_breadcrumb #project.name, #project
add_breadcrumb "List #{#category.display_name} Content", project_category_contents_path(#project, #category)
#contents_imported = Content.of_project(#project).with_category(#category).imported.order('contents.created_at asc')
#contents_not_imported = Content.of_project(#project).with_category(#category).not_imported.order('contents.created_at desc')
#page = params[:page]
imported = #contents_imported.where_values.reduce(:and)
not_imported = #contents_not_imported.where_values.reduce(:and)
#contents = Content.where(imported.or(not_ipmorted)).order('CASE contents.imported WHEN true THEN contents.created_at asc ELSE contents.created_at desc END')
#q = #contents.search(params[:q])
#content = #q.result(distinct: true).page(#page).per(20)
end
Now you can call Ransack#search on #contents because it is an ActiveRecord::Relation. I assume that the imported scope take a field contents.imported with value true.
If I wrote this without errors, this must works.

Filter controller result based on params

I'm trying to filter the results that are returned from my index view based on optional params. My code is working for the first param, sinceDate. But for the second param, searchQeury, nothing is filtered out.
_controller.rb
def index
since = params[:sinceDate]
query = params[:searchQuery]
#articles = Comfy::Cms::Page.published.all
if since
#articles = #articles.reject{ |a| a[:created_at] < Date.parse(since) }
end
if query
#article = #articles.select{ |a| a[:label].match(/#{query}/i) }
end
end
Is it possible that the problem is a typo?
In the line after "if query", it should be perhaps #articles instead of #article.

Resources