Reputation: 23
So my program has 2 models, Cars
and Payments
, where Payments is belong_to
Cars and is a one-to-many relationship.
I want to create a feature for calculating the accounts by going through the Payments' value and within a specific period. The user will give 2 inputs, start_date
and end_date
, then the program will calculate the total profit and expenses with the payments made within the period stated.
My question is, for the account part, should I create a Account Controller or creating new routes in the existing payment_controller
to calculate for the accounts part. If creating an Account Controller, how do I access the payments model from the Account Controller?
refer to this link for my project.
https://dl.dropboxusercontent.com/u/10960981/VKVINAUTO.rar
Or you could suggest a better method for me to proceed.
Upvotes: 0
Views: 64
Reputation: 76774
GIT
Firstly, you need to consider the use of git
or another Software Configuration Management system - which will give you the ability to properly manage the various elements of your code & its respective versioning.
Specifically, you shouldn't be posting RAR
file with your code. You'll be much better suited to using the likes of GitHub
or BitBucket
to store & share the relevant snippets of code you need help with.
You'll be best suited looking up about git
with this Railscast:
Fix
To answer your question about your fix, here's what you have to consider:
#config/routes.rb
root: "payments#index"
resources :cars do
resources :payments
end
#app/models/car.rb
class Car < ActiveRecord::Base
has_many :payments do
def dates begin, end
where("created_at >= begin AND created_at <= end")
end
end
end
#app/models/payment.rb
class Payment < ActiveRecord::Base
belongs_to :car
end
#app/controllers/cars_controller.rb
class PaymentsController < ApplicationController
def index
@car = Car.find params[:car_id]
@payments = @car.payments
if params[:begin].present? && params[:end].present?
@payments = @car.payments.dates(params[:begin], params[:end])
end
end
end
This will give you the ability to use the following:
#app/views/payments/index.html.erb
<%= form_tag car_payments_index(@car), method: :get do %>
<%= text_field_tag :begin %>
<%= text_field_tag :end %>
<%= submit_tag "Go">
<% end %>
This will essentially "refresh" the payments index page, determining the dates as you require.
Models
If you want to access the Payment
model from the accounts_controller
, you'll just be able to reference it by invoking it:
#app/controllers/accounts_controller.rb
class AccountsController < ApplicationController
def index
@payments = Payment.all
end
end
You'll want to read up on the MVC programming pattern, which Rails is built on. This will show you the relationship between Models
, views
and Controller
-- specifically, with them being interchangeable / exclusive
Upvotes: 2