I'm trying to add a line to my orders_items controller so if its a new order to increment the counter from zero to one. so have created an action that does that before the save is called but when I try it I get:
undefined method `+' for nil:NilClass
def create
#order_item = #order.order_items.find_or_initialize_by_product_id(params[:product_id])
# Error below
#order_item.quantity += 1
respond_to do |format|
if #order_item.save
end
end
order_item.rb:
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
validates :order_id, :product, presence: true
validates :quantity, numericality: { only_integer: true, greater_than: 0 }
def subtotal
quantity * product.price
end
end
order_items_controller.rb:
class OrderItemsController < ApplicationController
before_action :set_order_item, only: [:show, :edit, :destroy]
before_action :load_order, only: [:create]
# GET /order_items
# GET /order_items.json
def index
#order_items = OrderItem.all
end
# GET /order_items/new
def new
#order_item = OrderItem.new
end
# POST /order_items
# POST /order_items.json
def create
#order_item = #order.order_items.find_or_initialize_by_product_id(params[:product_id])
#order_item.quantity += 1
respond_to do |format|
if #order_item.save
format.html { redirect_to #order, notice: 'Successfully added product to cart.' }
format.json { render action: 'show', status: :created, location: #order_item }
else
format.html { render action: 'new' }
format.json { render json: #order_item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /order_items/1
# PATCH/PUT /order_items/1.json
def update
#order_item = OrderItem.find(params[:id])
respond_to do |format|
if order_item_params[:quantity].to_i == 0
#order_item.destroy
format.html { redirect_to #order_item.order, notice: 'Order item was successfully updated.' }
format.json { head :no_content }
elsif #order_item.update(order_item_params)
format.html { redirect_to #order_item.order, notice: 'Successfully updated the order item.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #order_item.errors, status: :unprocessable_entity}
end
end
end
# DELETE /order_items/1
# DELETE /order_items/1.json
def destroy
#order_item.destroy
respond_to do |format|
format.html { redirect_to #order_item.order }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def load_order
#order = Order.find_or_initialize_by_id(session[:order_id], status: "unsubmitted")
if #order.new_record?
#order.save!
session[:order_id] = #order.id
end
end
def set_order_item
#order_item = OrderItem.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_item_params
params.require(:order_item).permit(:product_id, :order_id, :quantity)
end
end
Migration file:
class AddDefaultQuantityToOrderItems < ActiveRecord::Migration
def change
change_column :order_items, :quantity, :integer, default: 0
end
end
rails console:
#order.order_items.find_or_initialize_by_product_id(params[:product_id])
NoMethodError: undefined method `order_items' for nil:NilClass
from (irb):1
from /usr/local/rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.4/lib/rails/commands/console.rb:90:in `start'
from /usr/local/rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.4/lib/rails/commands/console.rb:9:in `start'
from /usr/local/rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.4/lib/rails/commands.rb:62:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
Model order.rb:
class Order < ActiveRecord::Base
has_many :order_items, dependent: :destroy
def total
order_items.map(&:subtotal).sum
end
end
orders_controller.rb:
class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
# GET /orders
# GET /orders.json
def index
#orders = Order.all
end
# GET /orders/1
# GET /orders/1.json
def show
end
# GET /orders/new
def new
#order = Order.new
end
# GET /orders/1/edit
def edit
end
# POST /orders
# POST /orders.json
def create
#order = Order.new(order_params)
respond_to do |format|
if #order.save
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render action: 'show', status: :created, location: #order }
else
format.html { render action: 'new' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /orders/1
# PATCH/PUT /orders/1.json
def update
respond_to do |format|
if #order.update(order_params)
format.html { redirect_to #order, notice: 'Order was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
# DELETE /orders/1
# DELETE /orders/1.json
def destroy
#order.destroy
respond_to do |format|
format.html { redirect_to products_path }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
#order = Order.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order).permit(:user_id, :status)
end
end
Update
Rake routes shows route call for /:product_id
product.rb
class Product < ActiveRecord::Base
validates_numericality_of :price
validates :stock ,numericality: { greater_than_or_equal_to: 0 }
end
order.rb
# #Chiperific added proper 4-line indentation for SO viewing.
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
validates :order_id, :product, presence: true
validates :quantity, numericality: { only_integer: true, greater_than: 0 }
def subtotal
quantity * product.price
end
end
order items.rb
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
validates :order_id, :product, presence: true
validates :quantity, numericality: { only_integer: true, greater_than: 0 }
def subtotal
quantity * product.price
end
end
when i add
def create
#order_item = OrderItems.find_or_initialize_by_product_id(params[:product_id])
#order_item.quantity +=1
i get NameError in OrderItemsController#create - uninitialized constant OrderItemsController::Orderitems
def create
#order_item = Orderitems.find_or_initialize_by_product_id(params[:product_id]) <-error
#order_item.quantity += 1
if i try
#order = Order.find(params[:order_id])
#order_item = #order.order_items.find_or_initialize_by_product_id(params[:product_id])
#order_item.quantity += 1
i get ActiveRecord::RecordNotFound in OrderItemsController#create - Couldn't find Order without an ID
def create
#order = Order.find(params[:order_id])
#order_item = #order.order_items.find_or_initialize_by_product_id(params[:product_id])<-error
#order_item.quantity += 1
I don' t see where #order is defined. Since #order is null, #order_items will be as well.
I'm assuming your view URL is something like /orders/:order_id/order_items/:id
So let's use the URL parameter to make sure you get an Order or Order_ID initiated.
Option 1: Don't worry about #order
def create
#order_item = OrderItem.find_or_initialize_by_product_id(params[:product_id])
#order_item.quantity +=1
...
end
Option 2: Set the `#order` first
def create
#order = Order.find(params[:order_id])
#order_item = #order.order_items.find_or_initialize_by_product_id(params[:product_id])
#order_item.quantity += 1
...
end
Other potential problem:
.find_or_initialize_by_product_id(params[:product_id]) isn't actually finding or initializing.
It looks like this is your table relationship:
[Orders]`````\
|--> [Order_Items]
[Products]___/
I don't see where you have accepts_nested_attributes_for :order_items in orders.rb
You probably also need accepts_nested_attributes_for :order_items in products.rb
Does an Order_Item record have a Product_id field? I see where you're validating the presence of :product, but not :product_id, what does your schema look like? What happens if you try `find__or_initialize_by_product(params[:product_id])
Does your route call for /:product_id or /:product or neither? (a.k.a. is there a params[:product_id]?)
Update:
Thanks for the updated comments. Please add the whole URI being used, the whole Rake Routes line, or the Routes.rb file.
Or, while I know it's not SO-best-practice, you could post a link to the project on Github and I'll take a look there.
I'm still convinced that (at least one of) the issue(s) is that #order is not being set.
Trying it out in the Rails console is a great way to find out of .find_or_initialize_by_product_id is working
But, rails console can’t pull params and you still aren’t assigning #order first.
To test, in the rails console, try:
#order = Order.first #<----(just so you get #order assigned)
#order.order_items.find_or_initialize_by_product_id(1)
Also:
#order_item = OrderItems.find_or_initialize_by_product_id(params[:product_id])
OrderItems should be singular (my bad!!):
#order_item = OrderItem.find_or_initialize_by_product_id(params[:product_id])
I'll pay closer attention to this post and be more timely with my posts as I'm sure you're getting frustrated. Hang in there, your methodology is good.
But, there may be another way if we can't get these kinks worked out. Could we find the order item quantity by counting the # of records with a specific order id instead of saving the number statically in the database? Just a thought if you're ready to bail on this problem.
You can initialize #order_item.quantity by putting this in your OrderItem class:
def quantity
self.quantity ||= 0
end
Go into your method find_or_initialize_by_product_id, and make sure you initialize the attribute quantity to 0.
Here's a simple reproduction of your error - notice I never initialized x to 0:
$ irb
irb(main):001:0> x += 5
NoMethodError: undefined method `+' for nil:NilClass
from (irb):1
from /usr/bin/irb:11:in `<main>'
In Rails 4 you can use the following:
#order_item = #order.order_items.where(product_id: params[:product_id]).first_or_create
instead of
#order_item = #order.order_items.find_or_initialize_by_product_id(params[:product_id])
and this:
#order = Order.where(session[:order_id], status: "unsubmitted").first_or_initialize
instead of
#order = Order.find_or_initialize_by_id(session[:order_id], status: "unsubmitted")
Related
I wanted to upload image (using paperclip gem) to my product in my rails project, so i watched a youtube video how to do it (https://www.youtube.com/watch?v=Z5W-Y3aROVE) I did all he did, but i when i add a new product i get an error -
'New Product
2 errors prohibited this product from being saved:
Img url Paperclip::Errors::NotIdentifiedByImageMagickError
Img url has contents that are not what they are reported to be' , right above my new product form how do i fix it.
MY PRODUCT MODEL
class Product < ActiveRecord::Base
belongs_to :user
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings
has_attached_file :img_url, styles: { large: "800x600>", medium: "320x200>", thumb: "100x80#" }
validates_attachment_content_type :img_url, content_type: /\Aimage\/.*\z/
def self.tagged_with(name)
Tag.find_by!(name: name).products
end
def all_tags=(names)
# names="music, spotify"
self.tags = names.split(',').map do |name|
Tag.where(name: name).first_or_create!
end
end
def all_tags
tags.map(&:name).join(", ")
end
end
MY PRODUCTS_CONTROLLER
class ProductsController < ApplicationController
# before_action :authenticate_user!
before_action :set_product, only: [:show, :edit, :update, :destroy]
# GET /products
# GET /products.json
def index
if params[:tag]
#products = Product.tagged_with(params[:tag])
else
#products = Product.all
end
end
# GET /products/1
# GET /products/1.json
def show
end
# GET /products/new
def new
#product = Product.new
end
# GET /products/1/edit
def edit
end
# POST /products
# POST /products.json
def create
#product = current_user.products.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: #product }
else
format.html { render :new }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: #product }
else
format.html { render :edit }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
#product.destroy
respond_to do |format|
format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product
#product = current_user.products.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def product_params
params.require(:product).permit(:filetype, :title, :img_url, :description, :all_tags, :price, :uploaded_by, :tutorial_url)
end
end
and i displayed my images as
<%= link_to image_tag(product.img_url.url(:medium), :class =>"img-fluid tm-img"),product%>
building a shopping app but i don't want to show to listings of the same thing twice. I don't want it to show two listings for oranges. Instead I want it to show the quantity as 2.
I have changed the order_items_controller to show
#order_item = #order.order_items.find_or_initialize_by_product_id(params[:product_id])
#order_item.quantity += 1
get error undefined method `price' for nil:NilClass
tr>
<th>Order Total</th>
<td><%= print_price #order.total %></td> <- error
</tr>
<tr>
order_items.controller
class OrderItemsController < ApplicationController
before_action :set_order_item, only: [:show, :edit, :update, :destroy]
before_action :load_order, only: [:create]
# GET /order_items/1/edit
def edit
end
# POST /order_items
# POST /order_items.json
def create
#order_item = #order.order_items.find_or_initialize_by_product_id(params[:product_id])
respond_to do |format|
if #order_item.save
format.html { redirect_to #order, notice: 'Successfully Added Product To Cart.' }
format.json { render action: 'show', status: :created, location: #order_item }
else
format.html { render action: 'new' }
format.json { render json: #order_item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /order_items/1
# PATCH/PUT /order_items/1.json
def update
respond_to do |format|
if #order_item.update(order_item_params)
format.html { redirect_to #order_item, notice: 'Order item was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #order_item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /order_items/1
# DELETE /order_items/1.json
def destroy
#order_item.destroy
respond_to do |format|
format.html { redirect_to #order_item.order }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order_item
#order_item = OrderItem.find(params[:id])
end
def load_order
#order = Order.find_or_initialize_by_id(session[:order_id], status: "Unsubmitted")
if #order.new_record?
#order.save!
session[:order_id] = #order.id
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_item_params
params.require(:order_item).permit(:product_id, :order_id, :quantity)
end
end
orders.show.html
class OrderItemsController < ApplicationController
before_action :set_order_item, only: [:show, :edit, :update, :destroy]
before_action :load_order, only: [:create]
# GET /order_items/1/edit
def edit
end
# POST /order_items
# POST /order_items.json
def create
#order_item = #order.order_items.find_or_initialize_by_product_id(params[:product_id])
respond_to do |format|
if #order_item.save
format.html { redirect_to #order, notice: 'Successfully Added Product To Cart.' }
format.json { render action: 'show', status: :created, location: #order_item }
else
format.html { render action: 'new' }
format.json { render json: #order_item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /order_items/1
# PATCH/PUT /order_items/1.json
def update
respond_to do |format|
if #order_item.update(order_item_params)
format.html { redirect_to #order_item, notice: 'Order item was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #order_item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /order_items/1
# DELETE /order_items/1.json
def destroy
#order_item.destroy
respond_to do |format|
format.html { redirect_to #order_item.order }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order_item
#order_item = OrderItem.find(params[:id])
end
def load_order
#order = Order.find_or_initialize_by_id(session[:order_id], status: "Unsubmitted")
if #order.new_record?
#order.save!
session[:order_id] = #order.id
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_item_params
params.require(:order_item).permit(:product_id, :order_id, :quantity)
end
end
order.rb
class Order < ActiveRecord::Base
has_many :order_items, dependent: :destroy
def total
order_items.map(&:subtotal).sum
end
end
order_items.rb
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
validates :order_id, :product_id, presence: true
def subtotal
quantity * product.price
end
end
I have also created a table to add quantity
class AddDefaultQuantityToOrderItems < ActiveRecord::Migration
def change
change_column :order_items, :quantity, :integer, default: 0
end
end
The problem might be in your order model. You need 'self' to reference the current Order object. Change it to this
def total
self.order_items.map(&:subtotal).sum
end
In your create action for the order controller you need
#order = Order.find(<however you get the order id>)
you are trying to call a method on #order but you are not passing a value in the controller for that item as far as I can tell
I want show a daycare details on show page but I got this error
NoMethodError : undefined method `find' for nil:NilClass
from daycare controller file and i'm not get any idea. I have mentioned below that error line.
This is my Controller file
class DayCaresController < ApplicationController
before_filter :authenticate_user!
before_action :set_day_care, only: [:show, :edit, :update, :destroy]
# GET /day_cares
# GET /day_cares.json
def index
#day_cares = DayCare.all
end
# GET /day_cares/1
# GET /day_cares/1.json
def show
end
# GET /day_cares/new
def new
#day_care = DayCare.new
end
# GET /day_cares/1/edit
def edit
end
# POST /day_cares
# POST /day_cares.json
def create
#day_care = current_user.build_day_care(day_care_params)
respond_to do |format|
if #day_care.save
UserMailer.welcome_email(#user).deliver
format.html { redirect_to #day_care, :gflash => { :success => 'Day care was successfully created.'} }
format.json { render :show, status: :created, location: #day_care }
else
format.html { render :new }
format.json { render json: #day_care.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /day_cares/1
# PATCH/PUT /day_cares/1.json
def update
respond_to do |format|
if #day_care.update(day_care_params)
format.html { redirect_to #day_care, :gflash => { :success => 'Day care was successfully updated.'} }
format.json { render :show, status: :ok, location: #day_care }
else
format.html { render :edit }
format.json { render json: #day_care.errors, status: :unprocessable_entity }
end
end
end
# DELETE /day_cares/1
# DELETE /day_cares/1.json
def destroy
#day_care.destroy
respond_to do |format|
format.html { redirect_to day_cares_url, :gflash => { :success => 'Day care was successfully destroyed.'} }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions
def set_day_care
#day_care = current_user.day_care.find(params[:id]) # => **I got error this line**
end
# Never trust parameters from the scary internet, only allow the white list through.
def day_care_params
params.require(:day_care).permit(:name, :address, :office_phone, :cell_phone, :logo, :website, :user_id)
end
def dashboard
end
def profile
end
end
If user has_many: day_cares then use this name instead of day_care:
#day_care = current_user.day_cares.where(id: params[:id]).take
or probably as you wrote:
#day_care = current_user.day_cares.find(params[:id])
But with arrays instead of single instance (day_cares).
Also you can use just:
#day_care = DayCare.find(params[:id])
If you search by id. Or if you need to check that it's users day_care:
#day_care = DayCare.where(id: params[:id], user: current_user).take
current_user.day_care.find is not available, because you can only perform queries on plural associations. So given that the model associations are setup correctly as:
class User < ActiveRecord:Base
has_many :day_cares
...
end
the solution is probably just to resolve the spelling error from
`current_user.day_care.find` #wrong!
to
`current_user.day_cares.find` #right!
I want to edit a has_many through relation, but instead of editing the relation, it creates a new model.
In my form:
<%= form_for #service do |f| %>
<%= f.fields_for :service_users do |ac| %>
<% end %>
<% end %>
In my model:
class Service < ActiveRecord::Base
has_many :service_users
has_many :users, :through => :service_users
accepts_nested_attributes_for :service_users
end
Begin situation:
When i update the comments field:
After updating i see the edited relation as a duplication of the first one.
In some way i have to check if there're already relations present, but how?
Update:
My controller:
class ServicesController < ApplicationController
before_action :set_service, only: [:show, :edit, :update, :destroy, :users]
before_filter :authenticate_user!
# GET /services
# GET /services.json
def index
services = current_user.available_services
#available_services = services.group_by { |t| t.date.beginning_of_month }
end
# GET /services/1
# GET /services/1.json
def show
# service_users = current_user.service_users
#
# Service.find_each do |service|
# unless service_users.detect { |m| m.service_id == service.id }
# current_user.service_users.build service_id: service.id
# end
# end
#
#available_users = #service.available_users.group_by { |u| u.group }
#planned_users = #service.planned_users.group_by { |u| u.group }
#reserve_users = #service.reserve_users.group_by { |u| u.group }
end
# GET /services/new
def new
#service = Service.new
end
# GET /services/1/edit
def edit
#service.service_users.create
end
# POST /services
# POST /services.json
def create
#service = Service.new(service_params)
p service_params
respond_to do |format|
if #service.save
format.html { redirect_to #service, notice: 'Service was successfully created.' }
format.json { render action: 'show', status: :created, location: #service }
else
format.html { render action: 'new' }
format.json { render json: #service.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /services/1
# PATCH/PUT /services/1.json
def update
respond_to do |format|
p service_params[:service_users_attributes]
if #service.update(service_params)
format.html { redirect_to #service, notice: 'Service was successfully updated.' }
format.json { render action: 'show', status: :ok, location: #service }
else
format.html { render action: 'edit' }
format.json { render json: #service.errors, status: :unprocessable_entity }
end
end
end
def users
#users = #service.users
end
# DELETE /services/1
# DELETE /services/1.json
def destroy
#service.destroy
respond_to do |format|
format.html { redirect_to services_url }
format.json { head :no_content }
end
end
def destroy_association
if params[:id].present?
ServiceUser.find(params[:id]).delete
redirect_to root_path
end
end
def make_user_available_for_service
p '########'
p params
p #service
redirect_to root_path
end
private
# Use callbacks to share common setup or constraints between actions.
def set_service
#service = Service.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def service_params
params.require(:service).permit(:date, :comments,
service_users_attributes: [:user_id,
:service_id,
:availability,
:comments],
service_groups_attributes: [:service_id,
:group_id,
:start_time,
:end_time])
end
end
Try build instead of create.
Like this:
def edit
#service.service_users.build
end
And check your service_params.
Your missing an id for the service_users.
I am having a ridiculously hard time trying to figure out how to do this. I have been at it literally all day.
I have an Account class and a Transaction class.
Accounts are created with a balance and I want the Transaction amount, depending on its type, to either add or subtract from the balance.
I want to be able to update the Account balance every time a transaction is created. This is for a personal finance application. As of now when I create a new transaction, nothing happens to the account balance.
accounts_controller.rb
class AccountsController < ApplicationController
def index
#accounts = Account.all
end
def show
#account = Account.find(params[:id])
end
def new
#account = Account.new
end
def edit
#account = Account.find(params[:id])
end
def create
#account = Account.new(params[:account])
respond_to do |format|
if #account.save
format.html { redirect_to #account, notice: 'Account was successfully created.' }
format.json { render json: #account, status: :created, location: #account }
else
format.html { render action: "new" }
format.json { render json: #account.errors, status: :unprocessable_entity }
end
end
end
def update
#account = Account.find(params[:id])
respond_to do |format|
if #account.update_attributes(params[:account])
format.html { redirect_to #account, notice: 'Account was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #account.errors, status: :unprocessable_entity }
end
end
end
# DELETE /accounts/1
# DELETE /accounts/1.json
def destroy
#account = Account.find(params[:id])
#account.destroy
respond_to do |format|
format.html { redirect_to accounts_url }
format.json { head :no_content }
end
end
def update_balance
#a = Account.find(params[:id])
#a.transactions.each do |t|
#update_balance = t.t_type + #a.balance
#a.update_attributes(:balance => #update_balance)
end
end
end
transactions_controller.rb
class TransactionsController < ApplicationController
def create
#account = Account.find(params[:account_id])
#transaction = #account.transactions.create(params[:transaction])
redirect_to account_path(#account)
end
end
transaction.rb
class Transaction < ActiveRecord::Base
belongs_to :account
attr_accessible :amount, :category, :t_type
end
account.rb
class Account < ActiveRecord::Base
attr_accessible :balance, :name
has_many :transactions
end
If anyone has any idea what I'm doing wrong or can point me in the direction of a good thorough explanation, that would be great. I am so lost at this point.
Try this.
class Account < ActiveRecord::Base
attr_accessible :balance, :name
has_many :transactions
def update_with_transaction(transaction)
return unless self.transactions.include? transaction
if transaction.t_type.eql? SOME_TYPE
self.balance += transaction.ammount
else
self.balance -= transaction.ammount
end
save
end
end
class TransactionsController < ApplicationController
def create
account = Account.find(params[:account_id])
#transaction = account.transactions.create(params[:transaction])
account.update_with_transaction(#transaction)
redirect_to account_path(account)
end
end
It doesn’t update because you haven’t told it to. Create an after_create callback to do so:
class Transaction < ActiveRecord::Base
# ...
after_create :update_account_balance
private
def update_account_balance
account.balance += amount
account.save
end
end
Adjust as needed. Note that this won’t handle updates to a transaction’s amount, which is left as an exercise for the reader.