I'm currently developing a web application using Ruby on Rails. I have a controller which get two parameters :city and :sub_category.
I've a model named InterestPoint which belongs to a SubCategory and a City
Using what I read on the web, I end up doing this to list all InterestPoint matching the city and the category :
class SubCategoryController < ApplicationController
def index
#city = City.where(route_str: params[:city]).first
#sub_category = SubCategory.where(route_str: params[:sub_category]).first
#interest_point = InterestPoint.where(city_id: #city.id).where(sub_category_id: #sub_category.id)
end
end
My models :
class SubCategory < ActiveRecord::Base
has_many :interest_points
end
class City < ActiveRecord::Base
has_many :interest_points
end
class InterestPoint < ActiveRecord::Base
belongs_to :sub_category
belongs_to :city
end
Here is the route concerned :
get '/:city/:sub_category/' => 'sub_category#index'
It's running well, but RubyMine (my IDE) keeps telling me this is a bad practice : Only one model per controller should be used.
So, my question is, why is it a bad practice, and how can I do it "the right way" ?
My answer based on khaled_gomaa one :
Step 1, moved from SubCategory Controller to InterestPoint Controller since it's what the page is about.
Step 2, created scopes inside my InterestPoint Model :
scope :by_location, lambda { |str|
joins(:city).where('cities.route_str = ?', str)
}
scope :by_category, lambda { |str|
joins(:sub_category).where('sub_categories.route_str = ?', str)
}
Step 3, added Index action to my InterestPoint Controller :
def index
#interest_points = InterestPoint.by_location(params[:city]).by_category(params[:sub_category]).load
end
According to what I've got from you.
This controller should be InterestPoints Controller as its main
function is to display a list of all Interest points.
The interest point model should contain a method to
retrieve all interest points located in a given city and falling
under a given sub category and you just call it in the controller.
So you'll have something like this
class InterestPointsController < ApplicationController
def index
#interest_point = InterestPoint.located(params[:city]).categorized(params[:sub_category])
end
end
where in located and categorized are scopes in the interest point model
Related
I am trying to figure out my superclass mismatch error. All the posts I've read about this describe the problem as being that User is defined twice as a class in my application.
In my case, it isn't defined twice. I have a services folder and within that I have a user folder (for user service classes). In that user folder, I have a file called organisation_mapper_service.rb, with:
class User < ActiveRecord::Base
class OrganisationMapperService
def self.call(user: u)
new(user: user).call
end
def initialize(user: u)
self.user = user
end
def call
if matching_organisation.present?
# user.organisation_request.new(organisation_id: matching_organisation.id)
# user.update_attributes!(organisation_id: matching_organisation.id)
else
#SystemMailer.unmatched_organisation(user: user).deliver_now
end
end
private
attr_accessor :user
def matching_organisation
User::OrganisationMapperService.new(user).matching_organisation
end
end
end
Separate to that, I have my user model which defines user as:
class User < ApplicationRecord
I thought it should be fine to define the service class in the way I have because it inherits from ActiveRecord::Base rather than ApplicationRecord.
Can anyone see what I've done wrong here? Where else could I look for a second definition of User?
TAKING SERGIO'S SUGGESTION
I change the user organisation mapper service to open as follows:
class User::OrganisationMapperService < ActiveRecord::Base
But that then gives an error with my Users::OrgRequestsController which has new defined as follows:
def new
#all_organisations = Organisation.select(:title, :id).map { |org| [org.title, org.id] }
#org_request = OrgRequest.new#form(OrganisationRequest::Create)
matched_organisation = User::OrganisationMapperService.new(current_user).matching_organisation
#org_request.organisation_id = matched_organisation.try(:id)
end
the error message then says:
PG::UndefinedTable at /users/4/org_requests/new
ERROR: relation "user_organisation_mapper_services" does not exist
LINE 8: WHERE a.attrelid = '"user_organisation_mapper...
**TAKING SERGIO'S SUGGESTION (exactly) **
I change my service class to:
class User::OrganisationMapperService
But then I get an error that says:
wrong number of arguments (given 1, expected 0)
That error highlights this line of my service class:
def initialize(user: u)
self.user = user
end
I don't know what to do about that because I clearly have a user if there is an inheritance from user.
Even once you solve all your other issues, you actually have an infinite recursion going on.
User::OrganisationMapperService.call(user: User.first)
Is equivalent to calling:
User::OrganisationMapperService.new(user: User.first).call
Which internally calls matching_organisation, so is sort of equivalent to:
User::OrganisationMapperService.new(user: User.first).matching_organisation
Meanwhile, matching_organisation calls
User::OrganisationMapperService.new(user).matching_organisation
It's just going to go round and round in circles.
The only reason it doesn't is because of the wrong number of arguments (given 1, expected 0) error. This is because it should be User::OrganisationMapperService.new(user: user) rather than User::OrganisationMapperService.new(user) in your matching_organisation method.
Update in response to comment:
From what I understand, the User::OrganisationMapperService is a service class that does the job of finding some Organisation and then performing some sort of work.
The User::OrganisationMapperService#matching_organisation method should actually contain the code that returns the matching organisation for the given user. The implementation will completely depend on how you have structured your database, but I'll give a couple of examples to put you on the right track or give you ideas.
First, Your organisations table may have a user_id column. In this case you could do a simple query on the Organisation model and perform a search using the user's id:
class User::OrganisationMapperService
def matching_organisation
# find the organisation and cache the result
#matching_organisation ||= ::Organisation.where(user_id: user).first
end
end
Alternatively, you may have some sort of join table where there may be multiple Users at an Organisation (just for this example let us call this table 'employments'):
class Employment < ApplicationRecord
belongs_to :user
belongs_to :organisation
end
We can add scopes (this is a must read) to the Organisation model to assist with the query:
class Organisation < ApplicationRecord
has_many :employments
has_many :users, through: :employments
scope :for_user, ->(user) {
# return organisations belonging to this user
joins(:users).merge( Employment.where(user_id: user) )
}
end
Then finally, the OrganisationMapperService#matching_organisation method becomes:
class User::OrganisationMapperService
def matching_organisation
# find the organisation and cache the result
#matching_organisation ||= ::Organisation.for_user(user).first
end
end
You are defining User class with two separate parent classes. Don't do that.
It should be
class User::OrganisationMapperService
This way, your existing User class will be loaded and used, rather than a new one created.
I thought it should be fine to define the service class in the way I have because it inherits from ActiveRecord::Base rather than ApplicationRecord.
The service class in your example doesn't inherit from anything.
How can I create multiple associated objects automatically just after I save a new primary object?
For example
In Rails 4, I have three objects: Businesses, Budgets, and Categories.
#app/models/business.rb
class Business < ActiveRecord::Base
#attrs id, name
has_many :budgets
end
#app/models/budget.rb
class Budget < ActiveRecord::Base
#attrs id, business_id, department_id, value
belongs_to :business
belongs_to :category
end
#app/models/category.rb
class Category < ActiveRecord::Base
#attrs id, name
has_many :budgets
end
When I create a new Business, after saving the new Business, I would like to atomically create a Budget for each Category and give it value of $0. This way, when I go to show or edit a new Business, it will already have the associated Categories and Budgets, which can then be edited. Thus, upon creating a new Business, multiple new Budgets will be created, one for each Category, each with the value of 0.
I read this article: Rails 3, how add a associated record after creating a primary record (Books, Auto Add BookCharacter)
And I am wondering if I should use the after_create callback in the Business model and have the logic then exist in the Budgets controller (not exactly sure how to do this) or if I should add logic to the businesses_controller.rb in the 'new' call with something similar to:
#business = Business.new
#categories = Category.all
#categories.each do |category|
category.budget.build(:value => "0", :business_id => #business.id)
end
In my experience, it's best to avoid using callbacks unless it relates to a given model's persistence. In this case, letting a budget set it's own default value when one isn't supplied is good use of a callback. That also removes some complexity from your logic.
class Budget
before_validate :set_value
...
private
def set_value
self.value ||= 0
end
end
For the rest, I would create custom classes, each with a single responsibility, to systematically generate a new business. Here's an example. Keep in mind that this is not meant to be copy and pasted, it's just to illustrate a concept:
class BusinessGenerator < Struct.new(:business_params)
attr_reader :business
def generate
create_business
create_budgets
end
private
def create_business
#business = Business.create!(business_params)
end
def create_budgets
BudgetGenerator.new(#business).create
end
end
class BudgetGenerator < Struct.new(:business)
def generate
categories.each do |c|
business.budgets.create!(category: c)
end
end
private
def categories
Category.all
end
end
This is nice because it separates concerns and is easily extensible, testable and doesn't use Rails magic like accepts_nested_attributes_for. For example, if in the future you decide that not all businesses need a budget in every category, you can easily pass the ones you want as an argument to BudgetGenerator.
You'll instantiate the BusinessGenerator class in the controller:
class BusinessController < ActionController::Base
...
def create
generator = BusinessGenerator.new(business_params)
if generator.generate
flash[:success] = "Yay"
redirect_to generator.business
else
render :new
end
end
...
end
Some sticking points you might have with this approach include:
Returning validation errors to your business form
If the creation of a budget fails, you're stuck with a budget-less business. You can't wait to save business until after the budgets are created because there is no id to associate. Perhaps consider putting a transaction inside of the generator method.
Regardless of Brent Eicher's great advice, I've never experienced anything bad from using callbacks. If you don't mind using them, you could do the following (if you're setting the budget at 0 each time):
#app/models/business.rb
class Business < ActiveRecord::Base
before_create :build_budgets
private
def build_budgets
Category.all.each do |category|
self.budgets.build(category: category, value: "0")
end
end
end
--
Also, you need to make sure your budget foreign keys are correct.
I see you have department_id when Budget belongs_to Category. You should make this category_id or define the foreign_key:
#app/models/budget.rb
class Budget < ActiveRecord::Base
belongs_to :category, foreign_key: "department_id"
end
I ended up adding the logic to the create method in the Business controller to loop through all Categories and create a budget just after save. Note that I was lazy and didn't put in any error handling. :
def create
#business = Business.new(params[:business])
#results = #business.save
#categories = Categories.all
#categories.each do |category|
category.budgets.create(:amount => "0", :business_id => #business.id)
end
respond_to do |format|
...
end
end
I would like to know, whatever the association is (simple belongs_to, polymorphic ...), when I make an association like :
class Toto < ActiveRecord::Base
belongs_to :test_one
belongs_to :test_two
end
class TestOne < ActiveRecord::Base
has_many :totos
end
class TestTwo < ActiveRecord::Base
has_many :totos
end
and then
test_one = TestOne.create
test_two = TestTwo.create
test1 = test_one.totos.create
test2 = test_two.totos.create
I would like to know into a callback of Toto what object instantiate me. In this case, it's obviously test_one and then test_two. I know I could check ids for example but the problem is when i do :
test3 = test_one.totos.create(test_two: test_two)
I can't know if test3 was created through test_one or test_two.
Thank you.
According to your example, I understand that you want to identify the type of object which is associated to your totos object (has_many :totos).
Since there are multiple different objects that might be associated to your totos object through the has_many and belongs_to associations, you might want to perform some kind of verification first to identify the type of the associated object.
First Answer:
This will only work if you know beforehand all the object types that has_many :totos
if test3.respond_to?(:test_one)
test = test3.test_one
elsif test3.respond_to?(:test_two)
test = test3.test_two
end
Second Answer:
I found this on Stackoverflow, and it somehow answeres your question. So if I rephrase the answer to:
def get_belongs_to(object)
associated = []
object.class.reflect_on_all_associations(:belongs_to).map do |reflection|
associated << object.try(reflection.name)
end
associated.compact
end
This method will return an array of all objects associated to your totos object. This will also work when totos belongs to multiple objects say test_one and test_two at the same time. So the following:
associated_objects = get_belongs_to(test3)
and in your case associated_objects[0] will yield the object you desire.
Hope this helps.
Rails does not persist the data you're looking for, so you'll have to store it yourself if you want it. This means you'll need a migration for the new field:
rails generate migration AddOriginalParentTypeToTotos original_parent_type:string
rake db:migrate
You can then override the assignment methods so that the first parent assigned will assign the original_parent_type attribute (and it will remain the same once assigned):
class Toto < ActiveRecord::Base
def test_one=(val)
self[:original_parent_type] ||= 'test_one'
super
end
def test_one_id=(val)
self[:original_parent_type] ||= 'test_one'
super
end
def test_two=(val)
self[:original_parent_type] ||= 'test_two'
super
end
def test_two_id=(val)
self[:original_parent_type] ||= 'test_two'
super
end
end
You can then use send to add an original_parent method:
class Toto < ActiveRecord::Base
def original_parent
send(original_parent_type) if original_parent_type
end
end
I have a model Category and class method tickets_num which return the number of tickets that belongs to this category:
Category.first.tickets_num # => 2
class Category < ActiveRecord::Base
has_many :tickets
def tickets_num
self.tickets.count
end
end
I would like to do controller method "popular" which will return me 3 categories with the highest number of tickets_num , how can I do it in the most elegant way?
def popular
#categories = Category.order(tickets_num).all.limit(3)
end
my method doesn't work.
The following active record query should get you what you need. Not sure if there is a cleaner way to do that.
Category.select("categories.*, COUNT(tickets.id) AS t_count").joins(:tickets).group("categories.id").order("t_count DESC").limit(3)
I'm trying to retrieve an associated column named "contribution_amount" for each user but I'm getting undefined method error and I can't figure out why.
Controller has:
#payments = Payment.where(:contribution_date => Date.today).pluck(:user_id)
#users = User.where(:id => #payments).find_each do |user|
user.payments.contribution_amount
end
models have:
class User < ActiveRecord::Base
has_many :payments
end
class Payment < ActiveRecord::Base
belongs_to :user
end
Exact error in console is
`undefined method `contribution_amount' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Payment:0x007fb89b6b2c08>`
user.payments is a scope; that is, it represents a collection of Payment records. The contribution_amount method is only available on individual Payment records. You could say user.payments.first.contribution_amount, but I'm not sure that's your goal.
Are you trying to sum the contribution amounts? In that case, you'd want to use a method which aggregates collections of records: user.payments.sum(:contribution_amount).
Veering off-topic for a moment, it is generally better to push scoping methods down into your models. For example:
class User < ActiveRecord::Base
def self.with_payment_contribution_after(date)
joins(:payments).merge(Payment.with_contribution_after(date))
end
def self.with_contribution_amount
joins(:payments).group("users.id")
.select("users.*, sum(payments.contribution_amount) as contribution_amount")
end
end
class Payment < ActiveRecord::Base
def self.with_contribution_after(date)
where(:contribution_date => date)
end
end
# In your controller
#users = User.with_payment_contribution_after(Date.today)
.with_contribution_amount
# In a view somewhere
#users.first.contribution_amount
The advantages to structuring your code this way are:
Your scopes are not longer locked away in a controller method, so you can easily reuse them other places.
Your controller method can become simpler and more declarative. That is, it can express what information it wants, not how that information is acquired.
Breaking scopes down into smaller pieces implies that our code is better decomposed, and that which has been decomposed can be recomposed.
It's easier to test scopes via model unit tests then via controller testing.