No route matches(resources invested) - ruby-on-rails

In routes.rb I have:
resources :dtests do
resources :dquestions
end
All activities and routes of type "/ dtests/2/dquestions/3" working properly, but when I try to enter "dtests/2/dquestions", an error:
No route matches {:action=>"show", :controller=>"dquestions", :locale=>:en, :dtest_id=>#<Dquestion id: 1, question_text: "dfs", count_answer: 4, dtest_id: "1", created_at: "2013-06-01 09:32:41", updated_at: "2013-06-01 09:32:41">}
In server log:
Dquestion Load (0.5ms) SELECT "dquestions".* FROM "dquestions" WHERE "dquestions"."dtest_id" = 1
default_url_options is passed options: {}
Rendered dquestions/index.html.erb within layouts/application (39.5ms)
Completed 500 Internal Server Error in 106ms
ActionController::RoutingError
Tell me, please, what's the problem?

Look here:
:dtest_id=>#<Dquestion id: 1, question_text: "dfs", count_answer: 4, dtest_id: "1", created_at: "2013-06-01 09:32:41", updated_at: "2013-06-01 09:32:41">
Somehow you pass the whole object instead of the id. Can't tell why to_param is not automatically triggered.
Anyway just prepend .id to your object in the url helper.

Related

Undefined method 'unshift'

I'm creating a new Rails app with Rails 6 and I want to do something like this:
#items = Item.all.unshift Item.new(id: 0, name: '-- Kein Item --')
But I get the error "undefined method `unshift' for #<ActiveRecord::Relation [#<Item id: 1, name: "Item 1", created_at: "2021-03-13 11:09:34.284978000 +0000", updated_at: "2021-03-13 11:09:34.284978000 +0000">]>"
In another Rails app I can do it, but that app is running under Rails 4.
I want to add this "empty" record so that model project hast not everytime an item and because I have somewhere Project.item.name it won't give an nil error.
Any suggestions?

Rails website still at "Welcome aboard" where I expect to see content

I'm trying to build Rails blogger site following a tutorial, but I'm not seeing the expected web page. I've done the following:
1) I've modified the config/routes.rb file to look as follows:
Blogger::Application.routes.draw do
resources :articles
end
2) In db/migrate, there is a "_create_articles.rb" which I've modified to the following:
class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.string :title
t.text :body
t.timestamps
end
end
end
In the console, I've defined several instances of the "Article" class, assigned "title" and "body" attributes, and saved them, which I confirmed by calling "Article.all" in the console:
irb(main):001:0> Article.all
Article Load (1.7ms) SELECT "articles".* FROM "articles"
=> #<ActiveRecord::Relation [#<Article id: 1, title: "Sample Article Title", body: "This is the text for my article, woo hoo!", created_at: "2016-06-17 18:18:33", updated_at: "2016-06-17 18:18:33">, #<Article id: 2, title: "This is the second sample article", body: "Text for the second sample article", created_at: "2016-06-17 18:19:35", updated_at: "2016-06-17 18:19:35">, #<Article id: 3, title: "Third article!", body: "Lorem ipsum", created_at: "2016-06-17 18:20:01", updated_at: "2016-06-17 18:20:01">]>
I've also started the Rails server using the "rails server" command in project directory. However, if I go to localhost:3000 I still see the "Welcome aboard" screen (shown below), whereas I would expect at this point to see an error message "Unknown action - The action 'index' could not be found for ArticlesController".
In fact, I have been at this point before in the tutorial, but I've since closed everything and reopened it, and now I no longer see the website I expect, or any error message. Any ideas what could be amiss?
You need to set a root page in your routes.rb file to get rid of that page in development environment.
Blogger::Application.routes.draw do
resources :articles
root 'articles#index'
end

Basic ActiveModel methods not working on objects

I asked a question earlier about calling associated model attributes.
Specifically, I asked about trying to display the names of the Vip model instances associated with an event.
Initially I had
<% #organization.events.each do |event| %>
<p>
<table>
<tr>
<td>
<%= event.name %>
</td>
<td>
<%= event.vips.name %>
</td>
</tr>
</table>
</p>
<% end %>
Which I changed to
<%= event.vips.first.name %>
and it worked for a little while. I eventually adjusted it to
<% event.vips.each do |vip| %>
<%= vip.name %>
which also worked for a little while. But when I came back to the computer after taking a break, new event form submissions were no longer displaying the vip's name on the organization show page, even though the database was being updated with the vip_id foreign key.
In fact, when I tried
<%= event.vips.first.name %>
again, I got an error saying "undefined method `name' for nil:NilClass"
I'm really not sure what changed, or what I'm doing wrong. So any help would be appreciated.
Update:
To help clarify the problem, I get the following outputs from the console:
irb(main):005:0> Event.first
Event Load (0.2ms) SELECT "events".* FROM "events" ORDER BY "events"."id" ASC LIMIT 1
=> #<Event id: 1, when: "2015-08-25 00:00:00", organization_id: 1, created_at: "2015-08-25 04:47:43", updated_at: "2015-08-25 04:47:43", name: "John's Event", vip_id: 1>
irb(main):006:0> Vip.first
Vip Load (0.2ms) SELECT "vips".* FROM "vips" ORDER BY "vips"."id" ASC LIMIT 1
=> #<Vip id: 1, name: "John", created_at: "2015-08-25 04:46:23", updated_at: "2015-08-25 04:46:23", organization_id: 1, event_id: nil>
irb(main):007:0> #organization
=> #<Organization id: 1, name: "Test Org", created_at: "2015-08-25 04:46:03", updated_at: "2015-08-25 04:46:03", user_id: 1>
irb(main):008:0> #organization.events.first
=> #<Event id: 1, when: "2015-08-25 00:00:00", organization_id: 1, created_at: "2015-08-25 04:47:43", updated_at: "2015-08-25 04:47:43", name: "John's Event", vip_id: 1>
irb(main):009:0> #organization.events.first.vips
Vip Load (0.2ms) SELECT "vips".* FROM "vips" WHERE "vips"."event_id" = ? [["event_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy []>
irb(main):010:0>
Your event has no vips. Since event.vips is basically an empty array, calling #first on it returns nil. You then try to call #name on nil. But #name isn't a method of nil, hence the error undefined method 'name' for nil:NilClass.
Normally,
event.vips.first.name will return the error you received if event.vips.first is Nil (which just means that that specific event has no vips, because .first returned Nil or nothing).
In some other times however event.vips.first is a Vip record (which just means that that specific event has at least one Vip).
Since in my first Scenario it returned nil, then nil.name will obviously return an error. However, in my second scenario that it retuned vip, then vip.name will now work as you were expecting it to be.
You may try this if you want to disregard the error being raised: event.vips.first.try(:name)
Your code will work if update the event_id of vip
Vip.first.update_attribute event_id, Event.first.id
Issue happen because we don't have an association between Event.first and Vip.first
btw, I don't think we should use event.vips.first.name because vips can be empty
We can change it a little, ex:
event.vips.first.try(:name)
or
event.vips.map(&:name).join(", ")

Getting column value in Rails

I have a table named students.
I need to get email field from specific students
for example, I get the following output in IRB
Student.all
Student Load (0.1ms) SELECT "students".* FROM "students"
=> [#<Student id: 1, name: "Bob", grade: 1, email_address: "bob#school.com", created_at: "2014-03-27 08:55:51", updated_at: "2014-03-27 08:55:51">, #<Student id: 2, name: "Neo", grade: 1, email_address: "robert#neo.com", created_at: "2014-03-27 08:56:05", updated_at: "2014-03-27 08:56:05">, #<Student id: 3, name: "Phil", grade: 3, email_address: "phil#school.com", created_at: "2014-03-27 08:56:21", updated_at: "2014-03-27 08:56:21">]
now I need to get email addresses of grade 1 students.
How could I get it?
I solved it,
it can be done by using pluck function:
mail_addresses = Student.where(grade: 1).pluck(:email_address)
mail_addresses.each do|a|
puts a
end
Output :
bob#school.com
robert#neo.com
=> ["bob#school.com", "robert#neo.com"]
Voila!
I think that it will help you.
There are many way to write queries to get email addresses of student with grade 1.
Student.where(:grade => 1).map(&:email)
or
Student.where(:grade => 1).collect(&:email)
or
Student.where("grade = ?", 1).map(&:email)
or
Student.find(:all, :conditions => ["grade = ?", 1]).map(&:email)
you can use select also.
Student.where("grade = ?", 1).select("email").map(&:email)
always use rails query with where instead of find. rails query with `where' is working fast instead of find.

Why can't I destroy this variable in Ruby?

In the rails console, I do this:
input = Input.create :name => "foo"
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
Input.all
=> [#<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">]
input
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
input.destroy
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
> Input.all
=> []
> input
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
> input.reload
ActiveRecord::RecordNotFound: Couldn't find Input with id=8
> input
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
What I'd really expect to see is something like:
> input
=> nil
The object is deleted from the database but the variable still exists and is still trying to point to it. What's going on?
The input variable stores a reference to the instance in memory. Destroying the record will remove the row from the database. Calling input.reload (docs) raises an exception when attempting to find the record but doesn't set the value of your variable to nil on your behalf.
This behavior can be useful in the span of a DELETE request in which you want to display information about the object you removed. For example:
class WidgetsController < ApplicationController
def destroy
#widget = Widget.find(params[:id])
#widget.destroy
respond_with #widget, notice: "You successfully removed #{#widget.name}"
end
end
The destroy method makes the SQL call to the database and destroys the row in the table that contains it. It does still allow you to manipulate the object in the application as long as it’s still in scope (i.e) the callbacks and
filters are allowed even after destroying the object.
It is better to use "delete" if we don't want the callbacks to be triggered or if we want better performance
you can use input.delete

Resources