class Agency < ActiveRecord::Base
has_many :events
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :name, :email, :phone, :address, :city, :state, :zip,
:notes, :is_admin, :password, :password_confirmation, :remember_me
end
class Event < ActiveRecord::Base
belongs_to :agency
has_many :consumers
end
class Consumer < ActiveRecord::Base
belongs_to :event
end
In consumers_controller I am trying to include some field from agency
active_scaffold :consumer do |conf|
list.columns = [
:agency, :event
]
end
There are such associations Agency -> Event -> Consumer. And there is no association between agency and consumer, only through event.
but it causes an error.
How Can I include to list a any field form agency table?
According to the wiki, I think what you want is this:
active_scaffold :consumer do |conf|
conf.columns = [:agency, :event]
end
Also, make sure a consumer has an agency association or column.
Solution was a quite simple but most likely inefficient.
I have added a method to Consumer model:
class Consumer < ActiveRecord::Base
...
def agency_name
self.event.agency[:name]
end
end
Then I have added a virtual column to list:
list.columns = [
:agency_name, :event, ... ]
That's all.
Related
My problem is: I have a User model , Employee , Student, Parent. I don't know how to map each of Employee , Student, Parent back to User ID correctly. because in the current state for example I have differentiating by a normal user and an employee (since the employee is a user as well ) , How can I do so ? For example I will paste Employee and User and Ticket so you can help me to map it correctly because in my system Ticket model is not dealing with the Employee as a User . please I am stuck on this two days ago :(
In those models , user_id in the ticket model is refering to creator of tickets and employee id is refering to assigned employee and thats the error i need to map Employee back to User ID correctly
User.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :validatable,:confirmable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable,
:trackable, :lockable, :timeoutable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :user_name, :first_name, :last_name, :password, :password_confirmation, :remember_me,
:role_ids, :current_password, :user_type_id
attr_accessor :current_password
# attr_accessible :title, :body
has_many :assignments
has_many :roles, :through => :assignments
has_many :articles
has_many :comments
has_many :students
has_many :guardians
has_many :employees
has_many :tickets
has_many :permissions
belongs_to :user_type
accepts_nested_attributes_for :tickets
def has_role?(role_sym)
roles.any? { |r| r.role_name.underscore.to_sym == role_sym }
end
end
Employee.rb
class Employee < ActiveRecord::Base
# attr_accessible :title, :body
after_create :add_to_users
attr_accessible :employee_number, :joining_date, :first_name, :middle_name, :last_name,
:gender, :job_title, :employee_department_id, :qualification, :experience_detail,
:experience_year, :experience_month, :status_description, :date_of_birth, :marital_status,
:children_count, :father_name, :mother_name, :husband_name, :blood_group, :nationality_id,
:home_address_line1, :home_address_line2, :home_city, :home_state, :home_pin_code,
:office_address_line1, :office_address_line2, :office_city, :office_state, :office_pin_code,
:office_phone1, :office_phone2, :mobile_phone, :home_phone, :email, :fax, :user_id, :school_id,
:employee_category_id, :employee_position_id, :reporting_manager_id, :employee_grade_id,
:office_country_id, :home_country_id
belongs_to :employee_department
belongs_to :employee_category
belongs_to :employee_position
belongs_to :employee_grade
belongs_to :nationality, class_name: 'Country'
belongs_to :reporting_manager, class_name: "Employee"
belongs_to :school
belongs_to :user
has_many :tickets
def add_to_users
new_user = User.new
new_user.user_name = self.first_name
new_user.first_name = self.first_name
new_user.last_name = self.last_name
new_user.email = self.email
new_user.password = "123456"
new_user.password_confirmation = "123456"
new_user.user_type_id = 2
new_user.save
t = Employee.find(self.id)
t.user_id = new_user.id
t.save
end
def to_label
full_name = first_name + " " + last_name
end
def full_name
full_name = first_name + " " + last_name
end
end
Ticket.rb
class Ticket < ActiveRecord::Base
before_save :default_values
after_commit :close_solved
after_commit :close_canceled
before_create :assign_state
attr_accessible :description, :title, :employee_department_id, :user_id, :first_name,
:last_name , :email, :state_id, :employee_id, :ticket_state, :assign_state
belongs_to :employee_department
belongs_to :user
belongs_to :state
belongs_to :employee
has_many :replies
def default_values
self.state_id = 3 if self.state_id.nil?
end
def to_label
ticket_state.to_s
end
def close_solved
if self.ticket_state == "solved"
self.update_column(:ticket_state, "closed (solved)")
self.save!
end
end
def close_canceled
if self.ticket_state == "canceled"
self.update_column(:ticket_state, "closed (canceled)")
self.save!
end
end
def assign_state
if self.employee_id.nil?
self.assign_state = "un-assigned"
else
self.assign_state = "assigned"
end
end
Ticket.all.each do |ticket|
if ticket.ticket_state.blank?
ticket.ticket_state = 'open'
end
ticket.save
end
end
I have the following models:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
has_many :rulesets
end
class Ruleset < ActiveRecord::Base
attr_accessible :title, :game_id, :user_id
validates :game_id, presence: true
validates :user_id, presence: true
validates :title, presence: true
belongs_to :user
belongs_to :game
has_many :rules
end
class Rule < ActiveRecord::Base
attr_accessible :description, :ruleset_id
belongs_to :ruleset
validates :description, presence: true
validates :ruleset_id, presence: true
end
I have a controller called PagesController that controls the user dashboard, where I want to display the number of rulesets and number of rules that a user has. this is my controller
class PagesController < ApplicationController
def home
end
def dashboard
#rulesets = current_user.rulesets
end
end
In my dashboard view, I'm attempting to display the rulesets and rules counts as such:
<% if current_user.rulesets.any? %>
<li><%= #rulesets.count %> Ruleset</li>
<li><%= #rulesets.rules.count%> Rules</li>
<% end %>
This returns the right number of rulesets if I just try and count the rulesets. When I try and count the rules, I get this and "undefined method `rules'" error. How am I supposed to access the rules that are in the users' ruleset?
You need to count all of the rulesets and the rules for each ruleset. Use something like:
#rulesets.collect {|r| r.rules.count}.sum
Rules would be associated to a particular ruleset. You should specify the ruleset, by id, and then use the ".rules.count" to count all rules associated with THAT ruleset.
I have a has_many and has_many :through relationship that looks like this...
class Guestlist < ActiveRecord::Base
belongs_to :venues
has_many :patrons
has_many :users, :through => :patrons
attr_accessible :capacity, :end_time, :name, :start_time, :venue_id
end
class Patron < ActiveRecord::Base
belongs_to :guestlists
belongs_to :users
attr_accessible :guestlist_id, :user_id, :checked_in
end
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
has_many :patrons
has_many :guestlists, :through => :patrons
end
I am trying to access the users "through" guestlist object...
#guestlist = Guestlist.find(params[:id])
#guests = #guestlist.users.order('name ASC')
and the following error is thrown...
NoMethodError (undefined method `scoped' for Users:Module)
I've been searching all over for a solution but nothing works. Please help!
Looks something wrong with your associations in Model Patron. Singularize users and guestlists. Refer more here
class Patron < ActiveRecord::Base
belongs_to :guestlist
belongs_to :user
attr_accessible :guestlist_id, :user_id, :checked_in
end
I've four user models: Zone, Product, User, Group
I want to choose what Users can sell a Product in a Zone, this is what Group does, with a many to many relation to User and a foreign key to one Product and one Zone. So I have one group per pair Zone/Product. I will also need to set custom attributes on that many to many relation so I used has_many :through Sell (I was unable to find a better name to describe the relation between Group and User).
So I ended up having 5 models: Zone, Product, User, Group, Sell.
It works fine, but now I'd need to select the next user available in a Group.
I was thinking to exploit Sell.id to find the user assigned to the same group with an higher id, if not present choose the first one again (this allows me to create a ring chain).
It would be useful to have a Group.next_user method.
Unfortunatly I can't figure out how to do this, I'd need help to find the next user available in the group (or the 1st one if there are no more users).
Follows the code for models all the models:
################
# models/group.rb
################
class Group < ActiveRecord::Base
has_many :sells
has_many :users, :through => :sells
belongs_to :zone
belongs_to :product
attr_accessible :priority, :product_id, :user_ids, :zone_id
end
################
# models/zone.rb
################
class Zone < ActiveRecord::Base
belongs_to :location
has_many :cities
has_many :groups
attr_accessible :name, :location_id
validates :location, :presence => true
end
################
# models/user.rb
################
class User < ActiveRecord::Base
after_create :create_calendar
before_destroy :destroy_calendar
belongs_to :location
belongs_to :mall
has_one :event_calendar
has_many :sells
has_many :groups, :through => :sells
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable, :registerable,
# :recoverable, :rememberable,
devise :database_authenticatable, :trackable,
:validatable, :authentication_keys => [:username]
# Setup accessible (or protected) attributes for your model
attr_accessible :username, :password, :password_confirmation, :remember_me, :name,
:surname, :role, :location_id
# attr_accessible :title, :body
ROLES = %w[Admin Agente Hostess HostessAdmin]
validates_uniqueness_of :username, :case_sensitive => false
validates :username, :presence => true
validates_presence_of :role, :name, :surname, :location_id
validates :location, :presence => true
validates :role, :inclusion => { :in => ROLES, :message => "%{value} non รจ un ruolo valido." }
def display_name
"#{self.name} #{self.surname}"
end
def has_role?(role)
# convert the role string to a sybmol
self.role.downcase.gsub(/\s+/, "_").to_sym == role
end
private
def create_calendar
if self.has_role? :agente
calendar = EventCalendar.new({:user_id => self.id})
calendar.save()
end
end
def destroy_calendar
if self.has_role? :agente
calendar = EventCalendar.find_by_user_id(self.id)
calendar.destroy()
end
end
def email_required?
false
end
def email_changed?
false
end
end
################
# models/product.rb
################
class Product < ActiveRecord::Base
after_create :create_groups
before_destroy :destroy_groups
attr_accessible :name
def create_groups
for zone in Zone.all
group = Group.new({:zone_id => zone.id, :product_id => self.id})
group.save()
end
end
def destroy_groups
for zone in Zone.all
group = Group.find_by_product_id(self.id)
group.destroy
end
end
end
################
# models/sell.rb
################
class Sell < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
Can you give me some help to get this done? Thanks!
If I get this right then addd this to your User model
scope :next, lambda { |p| {:conditions => ["id > ?", p.id], :limit => 1, :order => "id"} }
and this to your group model
def self.next_user
return User.first if Group.users.blank?
next_user = User.next(Group.users.last).first
return next_user || Group.users.first
end
This should do the trick. I didn't write test for this so you should test it :)
This is a bit complicated and I'm not sure how to implement it. I have a User model and a Relationship model. Users are able to "follow" each other (just like twitter). The relationship model is all setup properly and works great.
Next, I have an Event model. Each user has_and_belongs_to_many events (many to many association between users and events). Users "attend" events.
What I would like to do is pull a list of all events that are
being attended by the current_user
are being attended by users that current_user is following.
If possible, I would like to have this list accessible via the User model so I can say current_user.event_feed and it will list all events as mentioned above.
Here are my models:
class Event < ActiveRecord::Base
attr_accessible :name,
:description,
:event_date,
:location,
:owner_id,
:category,
:photo
CATEGORIES = ['Music', 'Outdoors', 'Party']
has_and_belongs_to_many :users
and relationship model:
class Relationship < ActiveRecord::Base
attr_accessible :followed_id
belongs_to :follower, :class_name => "User"
belongs_to :followed, :class_name => "User"
validates :follower_id, :presence => true
validates :followed_id, :presence => true
end
and user model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation, :time_zone
has_and_belongs_to_many :events
has_many :relationships, :dependent => :destroy,
:foreign_key => "follower_id"
has_many :reverse_relationships, :dependent => :destroy,
:foreign_key => "followed_id",
:class_name => "Relationship"
has_many :following, :through => :relationships,
:source => :followed
has_many :followers, :through => :reverse_relationships,
:source => :follower
Thanks!
This is rails 3 only, but quite elegant (untested, hopefully my memory of habtm relationships is ok).
class User < ActiveRecord::Base
# ...
def event_feed
ids = self.followers.collect(&:id) << self.id
Event.includes(:users).where(["`users`.id IN (#{ids.join(',')})"])
end
# ...
end
Event Model:
scope :attended, where("event_date < #{Date.today}")
User Model:
# Returns collection of events that are attended by user and users she follows
def attended events
attended_events = []
attended_events << events.attended
followers.each do |follower|
attended_events << follower.events.attended
end
attended_events
end
1) being attended by the current_user and
This can be achieved simply by calling current_user.events
2) are being attended by users that current_user is following.
This is a little trickier. You want to end up with a flattened list of other user's events: current_user.following.collect { |friend| friend.events }.flatten #=> returns an array of followers' events
Since you want to display all events in a single list (from what I could gather), I think a presenter class would be useful:
class EventFeed
attr_accessor :event, :display_name
def initialize(event, name)
self.event = event
self.name = name
end
end
And now, adding them together to get to current_user.event_feed
class User
def event_feed; []; end
end
And gluing it all together:
current_user.events.each { |e| current_user.event_feed << EventFeed.new(e, 'YOU') }
current_user.following.each do |friend|
friend.events.each { |e| current_user.event_feed << EventFeed.new(e, friend.name) }
end
current_user.event_feed #=> an array of EventFeed objects where you can display "You are going to #{event.name}"
Of course this is pseudo code, but it should get you on the right track