Rails forms for nested attributes with checkboxes, show items that do no
exist too
I have a model NotificationPreference, that indicates if a particular user
wants to be notified about of a particular Event on a particular
Household. So NotificationPreference belongs_to user, household and event.
If a user doesn't want to be notified, the row doesn't exist on the table
NotificationPreference.
I want to make a page where a logged in user chooses for a particular
household if he wants to be notified (per sms and/or email -- two boolean
fields: sms, email) about each event. So user and household are already
defined and I'd like to have a form with a checkbox for each event that
exists.
Schema for NotificationPreference:
create_table "notification_preferences", :force => true do |t|
t.integer "user_id", :null => false
t.integer "event_type_id", :null => false
t.integer "household_id", :null => false
t.boolean "email", :default => false, :null => false
t.boolean "sms", :default => false, :null => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
I already have a method that gets if the user wants to be notified or
prepares the row if the row doesn't exist:
# Class User
def get_notification_preferences(household)
preferences = Hash.new
Event.all.each do |event|
preferences[event] = Hash.new
preference = NotificationPreference.where(user_id: self.id,
household_id: household.id,
event_id: event.id).first
if preference
preferences[event_type] = preference
else
preferences[event_type] = NotificationPreference.new(user_id:
self.id,
household_id:
household.id,
event_id:
event.id)
end
end
preferences
end
I've tried using Rails Nested Attributes but no success so far.
accepts_nested_attributes_for :notification_preferences on
User.http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
Any ideas? Thanks in advance!
No comments:
Post a Comment