简体   繁体   中英

Rails collection for user including 1 globally available

I'm working on an application to track donations. Each donation has a follow-up record. Each follow-up has a type. Follow-up types belong to users. I'm trying to have 3 options for the donation's follow-up:

nil: no follow up yet, this is the default 0: a follow up will NOT be needed 1-99: a follow up is recorded for a particular type for that user

When creating a follow-up, the user should have a collection of their available follow up types (this is easy) but all users should have an additional option of 0, or "no follow up needed"

Is it possible to add a globally available option to every user's collection? If so, how is that best accomplished?

I am not sure I fully understood your question, but I'll try to answer it:

I guess you show the available types for each users by doing this in the controller:

@available_follow_up_types = current_user.follow_ups.pluck(:your_type).uniq.compact

And then in the view:

select_tag :follow_up_type, options_for_select(@available_follow_up_types)

If yes then you could add an extra option in the select_tag :

@available_follow_up_types = current_user.follow_ups.pluck(:your_type).uniq.compact
@available_follow_up_types.push('no follow up needed')

And then in your controller's action receiving the params of the select_tag :

if params[:follow_up_type] == 'no follow up needed'
  current_user.follow_ups.where()
else
  # normal behavior
end
class Donation < ActiveRecord::Base
  has_one :follow_up, dependent: :destroy, inverse_of :follow_up

  scope :users, ->(*u) {
    joins(:follow_ups).merge(FollowUp.users(u))
  }

  scope :not, -> {
    joins(:follow_ups).merge(FollowUp.not)
  }
end

class FollowUp < ActiveRecord::Base
  belongs_to :user
  belongs_to :donation

  scope :users, ->(*u) {where(user_id: u.flatten.compact.uniq)} 
  scope :not, -> {where "type is null or type = 0"}
  scope :needed, -> {where "type > 0"}
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM