My delete buttons broke - Error with ActiveRecord - ruby-on-rails-3

This was working perfectly and now I'm not sure what happened.
Here are the errors:
ActiveRecord::RecordNotFound at /status_updates/92
Couldn't find User with id=92
and
ActiveRecord::RecordNotFound at /status_updates/delete_all
Couldn't find User with id=delete_all
What happens is I have users that have many status updates. 92 here should refer to status update 92 that belongs to this user.
I haven't changed any of my code directly relating to this so I suspect it has something to do with a change I tried to make with my coffee-script. (I removed it from my gem file, ran bundle install, and then decided to try to live with out removing it, so I put it back in the gem file, ran bundle install again... and that's it.)
Anyway, the error occurs when I'm in show.html and I'm clicking either of my delete buttons. Either the delete_all or delete for a singular status_update.
Here's the controller methods for all of these which I didn't change at all:
def show
#user = User.find(params[:id])
#status_updates = #user.status_update
end
def destroy
#status_update.destroy
flash[:success] = "Status update deleted!"
redirect_to status_update_path(current_user.id)
end
def delete_all
#all_status_updates = current_user.status_update
#all_status_updates.delete_all
flash[:success] = "All status updates deleted!"
redirect_to status_update_path(current_user.id)
end
In my console I can look up this user and check out it's status updates, and the status updates are all there as I expect them to be. Which is a good thing.
But ActiveRecord can't find them all of a sudden??
Oh yea.. and here is my gem file relating to status_updates for the delete_all button
resources :status_updates do
collection do
delete :delete_all
end
end
The delete buttons look like this:
<%= link_to "delete", status_update, method: :delete %>
<%= link_to "Reset Log", delete_all_status_updates_path, method: :delete, data: { confirm: "Are you sure? Once this log is reset there is no going back!"}%>
I put those there to demonstrate their paths.
This should teach me to write my test and push all my work to git instead of running unsecured :/
Thanks!

Your first problem is that most likely you don't have javascript properly enabled. In Rails the delete method is done via javascript. Make sure you include all js files properly in your layout and application.js. You need to have either prototype or jquery.

Related

Rails 5 Minitest ActionView::Template::Error: nil is not a valid asset source

I upgraded my Rails Application from 4.2 -> 5.0.0.1.
Other TESTS works fine (e.g. Model, Helper, Feature), but havinf trouble with my Controller Test.
I have read about Keyword arguments in controller & integration tests in Rails 5. So I changed the code structure as given below...
ActionView::Template::Error: nil is not a valid asset source
setup do
#logo = plogos(:main_logo)
end
test "should get edit" do
puts #logo.id // just to check...working fine
get :edit, params: {id: #logo.id}
assert_response :success
end
But I got new error with ActionView.
Is there anyone encountered and fixed the same issue, please help!
Thank you!
You may want to add some logtrace, probably it hints you where it went wrong.
May it be that the main_logo-fixture doesn't have an image? Since Rails 5 image_tag raises this error when given an nil-value, see also: Rails, "nil is not a valid asset source" for a particular image_tag (Carrierwave)
Besides that, typically the new scaffolded code would look as follows:
require 'test_helper'
class LogosControllerTest < ActionDispatch::IntegrationTest
setup do
#logo = plogos(:main_logo)
end
#...
test "should get edit" do
get edit_logo_url(#logo)
assert_response :success
end
#...
end

Devise: "def create" in users_controller.rb not working?

I've been pulling my hair out trying to get anything working with "def create" and "def update" in the users_controller.rb for Devise.
For instance, I've tried this:
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
flash[:notice] = "Test Save"
else
flash[:notice] = "Test Error"
end
end
end
I've used this code along with the appropriate code to show flash notices in the views section. However nothing is shown when I either submit a blank form, an incomplete form, or a complete form. The user registration will still go through on a complete form, but it does not follow anything I put in "def create". I've tried other ways of testing this aside from flash notices, such as sending to a different page, etc. I get no response. The same thing for "def update", it doesn't seem to even use that code.
I'm completely dumbfounded on this one, any ideas?
If i understand your question correctly, you should be overwriting the devise controller.
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def new
super
end
def create
# add custom create logic here
end
def update
super
end
end
You can see what the default devise controllers are doing here:
https://github.com/plataformatec/devise/tree/master/app/controllers/devise
If you just want to edit the flash message, looking at the link above shows that devise uses a method called set_flash_message
# Sets the flash message with :key, using I18n. By default you are able
# to setup your messages using specific resource scope, and if no one is
# found we look to default scope.
# Example (i18n locale file):
#
# en:
# devise:
# registrations:
# signed_up: 'Welcome! You have signed up successfully.'
So you can just edit your devise.en.yml file with the correct text and voila!
Note: If you do overwrite the controller don't forget to also add
# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}
How about this instead?
if #user.save
redirect_to #user, notice: 'User was successfully created.'
else
render action: 'new'
end
You are setting the flash, but no redirection and no rendering. I'm wondering if you are getting a blank page, or a 200 with no body.
This will redirect to the show action, setting a flash notice if successful and render the new form with the #user.errors showing why it failed.
If you are using devise, you could use the Registrations Controller to create a new account, you shouldn't need to create a new one. If you create a new one, there might be a conflict in the routes with registrations#create and users#create both pointing to POST /users

Correct routing for short url by username in Rails

I am trying to replace user profile views of the sort
/users/1
with
/username
I'm aware this means I'll need to check for collisions of various kinds. I've consulted the following similar SO questions:
Ruby on rails routing matching username
customize rails url with username
Routing in Rails making the Username an URL:
routing error with :username in url
Here are the various failed routes.rb route definitions I've tried, and associated errors:
match "/:username" => "users#show", via: "get"
Here's the error:
ActiveRecord::RecordNotFound in UsersController#show
Couldn't find User without an ID
app/controllers/users_controller.rb:7:in `show'
Here is my corresponding users_controller:
6 def show
7 #user = User.find(params[:id])
8 end
match "/:username" => 'users#show', :as => :profile
Same error as above.
match "/:username", :controller => "users/:id", :action => 'show'
Routing Error
uninitialized constant Users
Try running rake routes for more information on available routes.
match '/:username', :controller => 'users', :action => 'show'
Same error as 1.
match '/:username', to: 'users/:id', via: 'show'
Server does not start.
match "/:username" => redirect("/users/:id")
Error:
ActiveRecord::RecordNotFound in UsersController#show
Couldn't find User with id=:id
Any idea why my routing is not working the same way that everyone else who asks this question's is?
Update
Just to take this issue out of the comments and put it in the question more cleanly. After making the change by #Ryan Bigg below, I had a routing problem in my redirect to profile when a new one is created. Here's my create code:
def create
#user = User.new(params[:user])
if #user.save
session[:user_id] = #user.id
flash[:success] = "Thank you for signing up."
redirect_to ('/'+#user.username)
#redirect_to #user, notice: "Thank you for signing up!"
else
render "new"
end
end
And here is my user.rb
def to_param
self.username
#username
end
However, the commented out redirect, which I think should work with the to_param update, doesn't work, while the ugly hackish one above it does. Why is the to_param overwrite, which worked for other people, not working on my app? My #update and #edit methods are also not working, as their redirects go to "users/1/edit" instead of "username/edit" if overwriting to_param doesn't take care of this.
The first one is correct, but isn't working because you're still attempting to do something like this inside your controller:
User.find(params[:username])
When you should instead be doing this:
User.find_by_username!(params[:username])
The first one will attempt to find by the primary key of your table, where the second one will, correctly, query on the username field instead.
In addition to the update for to_params, the bottom of the routes file needs the following line:
resources :users, :path => '/'

Activeadmin disabling the "new resource" method

I'm using Activeadmin for the admin interface on an app I'm working on (loving it) and I am curious if there is a way to disable the "New Resource" link in the upper-right corner of the resource show page?
The particular resource I'm using is nested inside another resource and I have a partial that allows it to be created from the show page on that parent resource.
I have disabled the resource in the menu, but I'd rather leave the resource in the menu so I can see/edit/delete those resources without having to find it by looking through its parent resource.
Previous solution didn`t work for me, so here is general solutions, that works always:
ActiveAdmin.register Book do
actions :index
#or like that
#actions :all, :except => [:destroy]
index do
column :title
column :author
end
end
Try config.clear_action_items! to remove the link to New and other links on top of the table
This removed the "New Resource" button from the top-right:
config.clear_action_items!
This removed both the "New Resource" button as well as the box "There are no resources yet - create one".
actions :all, :except => [:new]
Thank you, Irio
config.clear_action_items!
Will remove all the actions.
If you only want to remove the new action link you can also use:
config.remove_action_item(:new)
I know this is an old question, but I just came up to it (had the same problem), and realized that config.clear_action_items! and actions :all, :except => [:new] are fundamentally different.
config.clear_action_items! will remove the New button from the index page, while actions :all, :except => [:new] will remove both the button, AND the route, meaning you can't call it from another place (which, in my case, is needed).
I did this:
controller do
def action_methods
if some_condition
super
else
super - ['new', 'create', 'destroy']
end
end
end
To disable some of the possible actions. action_methods returns an array of the 7 standard CRUD actions, so you can subtract those you don’t want
Or even:
ActiveAdmin.register Purchase do
config.clear_action_items!
actions :index
end
Worked for me too ! :-)
ActiveAdmin.register AssetSumView do
menu :label => "Asset Summary View", :parent => "Things"
# no button for NEW (since this is a db view)
#---------------------------------------------------------------------------------------------
config.clear_action_items!
enter code here
action_item do
link_to "Assets" , "/admin/assets"
end
action_item do
link_to "AssetCatgCodes", "/admin/asset_catg_codes"
end
#---------------------------------------------------------------------------------------------
config.clear_action_items! does only half of the job. There is one issue though.
In case of empty index table, active admin show this message
There are no [Resources] yet. Create one
which doesn't get hidden by the above command and I don't want to entirely disable the action. So, I kept the link and edited the new action to redirect to the parent resource index with a message.
controller do
def new
if params[:parent_id].present?
super
else
redirect_to parent_resources_path, notice: "Create Resource through ParentResource"
end
end
end

FactoryGirl + RSpec + Rails 3 'undefined method <attribute>='

I'm fairly new to rails and TDD (as will no doubt be obvious from my post) and am having a hard time wrapping my brain around Rspec and FactoryGirl.
I'm using Rails 3, rspec and factory girl:
gem 'rails', '3.0.3'
# ...
gem 'rspec-rails', '~>2.4.0'
gem 'factory_girl_rails'
I have a user model that I've been successfully running tests on during development, but then needed to add an attribute to, called "source". It's for determining where the user record originally came from (local vs LDAP).
In my factories.rb file, I have several factories defined, that look something like the following:
# An alumnus account tied to LDAP
Factory.define :alumnus, :class => User do |f|
f.first_name "Mickey"
f.last_name "Mouse"
f.username "mickeymouse"
f.password "strongpassword"
f.source "directory"
end
I have a macro defined (that's been working up until now) that looks like this:
def login(user)
before(:each) do
sign_out :user
sign_in Factory.create(user)
end
end
I'm calling it in multiple specs like so (example from users_controller_spec.rb):
describe "for non-admins or managers" do
login(:alumnus)
it "should deny access" do
get :index
response.should redirect_to(destroy_user_session_path)
end
end
If I don't specify the "source" attribute, everything works OK, but as soon as I do, I get an error like so when running the test
12) UsersController for non-admins or managers should deny access
Failure/Error: Unable to find matching line from backtrace
NoMethodError:
undefined method `source=' for #<User:0x00000100e256c0>
I can access the attribute no problem from the rails console and the app itself, and it's listed in my attr_accessible in the user model. It's almost as though Rspec is seeing an old version of my model and not recognizing that I've added an attribute to it. But if I put the following line into my user model, the error disappears
attr_accessor :source
... which indicates to me that it is actually looking at the correct model.
Help!
How about running this?
rake db:test:load
[If you added a new attribute you'd need to migrate it to the test database.]
if you don't use schema.rb (e.g. you have set config.active_record.schema_format = :sql)
you should run
rake db:test:prepare