Is there a better way to ensure that I don't delete the last record of a relation? I feel like this should be done through a validation, but could not make that stop the destroy action.
FYI - #organization is present because nested routes
class LocationsController < ApplicationController
....
....
def destroy
#organization = Organization.find(params[:organization_id])
#location = #organization.locations.find(params[:id])
count = Location.find_all_by_organization_id(#location.organization_id).count
if count > 1
#location.destroy
flash[:notice] = "Successfully destroyed location."
redirect_to #organization
else
flash[:notice] = "Could not destroy the only location."
redirect_to #organization
end
end
end
You might also consider the before_destroy callback (though I don't think your version is all that bad):
http://edgeguides.rubyonrails.org/active_record_validations_callbacks.html#destroying-an-object
Related
I'm new to learning Rails 3 and working through a Q&A app tutorial. I'm just wondering why I can't do this (I get an error) in relating a particular answer to a question. It works for the current user...
class AnswersController < ApplicationController
before_filter :auth, only: [:create]
def create
#question = Question.find(params[:question_id])
**#answer = Answer.new(params[:answer])
#answer.question = #question
#answer.user = current_user**
if #answer.save
flash[:success] = 'Your answer has been posted!'
redirect_to #question
else
#question = Question.find(params[:question_id])
render 'questions/show'
end
end
end
The tutorial says that this is the correct way:
class AnswersController < ApplicationController
before_filter :auth, only: [:create]
def create
#question = Question.find(params[:question_id])
**#answer = #question.answers.build(params[:answer])**
#answer.user = current_user
if #answer.save
flash[:success] = 'Your answer has been posted!'
redirect_to #question
else
#question = Question.find(params[:question_id])
render 'questions/show'
end
end
end
Doing the following
#answer = #question.answers.build(params[:answer)
Is the same as doing this
#answer = Answer.new(params[:answer])
#answer.question_id = #question.id
Doing a build adds the relation attributes to the new answer, in this case question_id
As for the error, can you provide the type of error you receive?
I'm experiencing a bizarre issue testing a destroy method. I'm using FactoryGirl and Rspec.
Here's a look at the method in question. As you can see, it doesn't actually destroy the dealer, just set it and it's dependent object's active attributes to false:
dealers_controller.rb
def destroy
#dealer = Dealer.find(params[:id])
#dealer.active = false
#dealer.save!
#dealer.leads.each { |lead|
lead.active = false
lead.save!
}
#dealer.users.each { |user|
user.active = false
user.save!
}
redirect_to dealers_path
end
When I run this method in the application it does exactly what it should do. Now, on to the test.
dealers_controller_spec.rb
describe "#destroy" do
context "when deleting a valid record" do
let(:dealer) { FactoryGirl.create(:dealer_with_stuff) }
before do
#user = FactoryGirl.build(:admin_user)
login_user
delete :destroy, :id => dealer.id
end
it { should assign_to(:dealer).with(dealer) }
it { should redirect_to(dealers_path) }
it { should set_the_flash }
it "is no longer active" do
dealer.active.should be_false
end
it "has no active users" do
dealer.users.each do |user|
user.active.should be_false
end
end
it "has no active leads" do
dealer.leads.each do |lead|
lead.active.should be_false
end
end
end
end
The first 3 tests pass, but the last 3 all fail (weirdly, the user.active.should be_false test only fails if I put a sleep(10) after delete :destroy up above, but let's not get into that issue now). So when I check the test log, it goes through the entire destroy process, but then does a ROLLBACK, so for some reason it doesn't save any of the records; but it doesn't give me any more information than that.
Does anyone have any thoughts on this? I've tried everything I can possibly think of.
What if you reload the dealer? The dealer in your tests is different from the #dealer object in the controller (ActiveRecord doesn't do identity maps).
before do
#user = FactoryGirl.build(:admin_user)
login_user
delete :destroy, :id => dealer.id
dealer.reload # << add this
end
I am using ruby 1.9.2-p180, rails 3.0.7. I have used validates_acceptance_of since the user has to agree to our terms and conditions. We don't have a column for this, but I understand that "If the database column does not exist, the terms_of_service attribute is entirely virtual. " from http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000082
Anyway, I double checked this by smoke testing the app manually and I see from the logs that the record is still inserted into the db, which is weird because upon submitting the form, I am redirected back to the form with the error: "Must agree to terms and conditions"(which made me think it worked before)
Am I doing something wrong here?
_form.haml:
%label.checkbox-label{:for => "operator_terms_and_conditions"}
= f.check_box :terms_and_conditions
I agree to
= link_to "Terms and Conditions", operator_terms_path, :target => "_blank"
operators_controller:
def create
user_params = params[:operator][:user]
user_params.merge!(:login => user_params[:email])
#password = params[:operator][:user][:password]
Operator.transaction do # don't save User if operator is invalid
#operator = Operator.create(params[:operator])
end
respond_to do |format|
unless #operator.new_record?
UserMailer.operator_confirmation_email(#operator, #password).deliver
UserMailer.operator_registration_admin_notification_email(#operator).deliver
UserSession.create(#operator.user)
format.html {redirect_to new_operator_aircraft_path}
else
format.html { render :action => "new" }
end
end
end
and in the model:
validates_acceptance_of :terms_and_conditions
Found the answer. The problem was not with validates_acceptance_of but rather with how I was saving the data. When an operator was created, a user was also created that was tied to it and it was this user that was being inserted into the db.
This happens because although the operator was being rolled back(because it wasn't valid) the user was still created(because it was not in a transaction).
I solved this by using nested_transactions:
operator model:
...
User.transaction(:requires_new => true) do
create_user
raise ActiveRecord::Rollback unless self.valid?
end
...
I have a basic rails question where I need to save two associated objects.
The association is Rtake has_many :companies and Company belongs_to :rtake
def create
#rtake = RTake.new(:email => params[:contact_email])
#rtake.role = "PROVIDER"
#company = #rtake.companies.build(params[:company])
#company.rtake = #rtake
respond_to do |format|
if #company.save_company_and_rtake
format.html{ redirect_to admin_companies_url}
else
flash.now[:errors] = #company.errors.full_messages.join(", ")
format.html{ render "new" }
end
end
end
In my company.rb class I have
def save_company_and_rtake
status1 = self.save(:validate => false)
status2 = self.rtake.save(:validate => false)
status = status1 && status2
status
end
The problem I face is that the company.rtake_id remains nil. Ideally shouldn't the company.rtake_id get updated to the #rtake.id after save.
I know I am missing something basic. Would appreciate some help.
You shouldn't need this line:
#company.rtake = #invitation
#invitation is nil from what you've shown .
But also, when you built the #company, #rtake.id isn't set because it hasn't been saved.
#company = #rtake.companies.build(params[:company])
#company.rtake = #rtake
#rtake.companies.build(params[:company]) This already means #company.rtake == #rtake. it's redundent here.
I have a Trans (transaction) class in my application that submits a transaction to the server. When a transaction is submitted, I also want to do an update on a parent User class to update their cached "balance." Here is relevant code:
# tran.rb
class Tran < ActiveRecord::Base
belongs_to :submitting_user, :class_name => 'User'
end
And my controller:
#trans_controller.rb
def create
#title = "Create Transaction"
# Add the transaction from the client
#tran = Tran.new(params[:tran])
# Update the current user
#tran.submitting_user_id = current_user.id
# ERROR: This line is not persisted
#tran.submitting_user.current_balance = 4;
# Save the transaction
if #tran.save
flash[:success] = 'Transaction was successfully created.'
redirect_to trans_path
I have a couple of problems:
When I update the current_balance field on the user, that balance isn't persisted on the user after the transaction is saved. I think maybe I need to use update_attributes?
I am not even sure that the code should be a part of my controller - maybe it makes more sense in the before_save of my model?
Will either of these make this transactional?
def create
title = "Create Transaction"
#tran = Tran.new(params[:tran])
#tran.submitting_user_id = current_user.id
# to make it "transactional" you should put it after #tran.save
if #tran.save
current_user.update_attribute :current_balance, 4
...
And yes - it is better to put it into after_save callback
class Tran < AR::Base
after_save :update_user_balance
private
def update_user_balance
submitting_user.update_attribute :current_balance, 4
end
end