Skip to content

Instantly share code, notes, and snippets.

@majornorth
Last active December 18, 2015 19:48
Show Gist options
  • Save majornorth/5835067 to your computer and use it in GitHub Desktop.
Save majornorth/5835067 to your computer and use it in GitHub Desktop.
I need to figure out a way to save :status (an attribute of the event model) if it meets the condition and is set to "full". I tried using @event.update_attributes(params[:status]), but that didn't work. I've also tried @status.save and just save, but those result in "undefined method errors". Suggestions?
class Event < ActiveRecord::Base
attr_accessible :needed, :start, :location, :league, :skill_level, :field_type, :organizer, :note, :status
has_and_belongs_to_many :users
end
def join
@event = Event.find(params[:event][:event_id]).users << current_user
@attendees = Event.find(params[:event][:event_id]).users
@needed = Event.find(params[:event][:event_id]).needed
@status = Event.find(params[:event][:event_id]).status
if @attendees == @needed
@status = "full"
end
redirect_to :back
end
create_table "events", :force => true do |t|
t.datetime "start"
t.text "location"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "organizer"
t.integer "needed", :default => 1
t.string "league"
t.string "field_type"
t.string "skill_level"
t.text "note"
t.string "status"
end
@majornorth
Copy link
Author

I found that, using the console, writing:

Event.find(20).update_attributes(:status => "full")

actually updates the attribute in the db. Now, trying to use that same logic inside the controller.

@majornorth
Copy link
Author

WOO!

Figured it out (thanks to this post http://www.davidverhasselt.com/2011/06/28/5-ways-to-set-attributes-in-activerecord/)

Here are the action controllers that I wrote:

def join
@add_user = Event.find(params[:event][:event_id]).users << current_user
@attendees = Event.find(params[:event][:event_id]).users.count
@Needed = Event.find(params[:event][:event_id]).needed
@event = Event.find(params[:event][:event_id])
if @attendees == @Needed
@event.update_attributes(:status => "full")
end
redirect_to :back
end

def leave
@event = Event.find(params[:event][:event_id]).users.delete(current_user)
@attendees = Event.find(params[:event][:event_id]).users.count
@Needed = Event.find(params[:event][:event_id]).needed
@event = Event.find(params[:event][:event_id])
if @attendees < @Needed
@event.update_attributes(:status => "open")
end
redirect_to :back
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment