Syntax Error in UserFriendshipsController#index - ruby-on-rails

I am getting a SyntaxError in UserFriendshipsController#index for:
#user_friendship = current_user.user_friendships.all
I am not sure what I missed. Any assistance will be greatly appreciated! I'm still new to rails. Thanks in advance!
Controller
class UserFriendshipsController < ApplicationController
before_filter :authenticate_user!
def index
#user_friendships = current_user.user_friendships.all
end
def accept
#user_friendship = current_user.user_friendships.find(params [:id])
if #user_friendship.accept!
flash[:success] = "You are now friends with #{#user_friendship.friend.name}"
else
flash[:error] = "That friendship could not be accepted"
redirect_to user_friendships_path
end
def new
if params[:friend_id]
#friend = User.find(params[:friend_id])
#user_friendship = current_user.user_friendships.new(friend: #friend)
else
flash[:error] = "Friend required"
end
rescue ActiveRecord::RecordNotFound
render file: 'public/404', status: :not_found
end
def create
if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id)
#friend = User.find(params[:user_friendship][:friend_id])
#user_friendship = current_user.user_friendships.new(friend: #friend)
if #user_friendship.save
flash[:success] = "You are now friends!"
else
flash[:error] = "There was a problem."
end
redirect_to user_path(#friend)
else
flash[:error] = "Friend required"
redirect_to root_path
end
end
def edit
end
end
end
Index
<% #user_Friendships.each do |friendship| %>
<% friend = friendship.friend %>
<div id="<%= dom_id(friendship) %>" class="friend row">
<div class="span1">
<center><%= link_to image_tag(user.avatar.url(:thumb)), user %></center>
</div>
<div class="span7">
<strong><%= friend.name %></strong><br />
<%if friendship.pending? %>
<em>Frienship is pending.</em> <%=link_to "Delete request", edit_user_friendship_path(friendship) %>.
<% end %>
<% if friendship.requested? %>
<em>Friendship requested.</em> <%= link_to "Accept Friendship", edit_user_friendship_path(friendship) %>.
<% end %>
<% if friendship.accepted? %>
<em>Friendship started <%= friendship.updated_at %>.</em> <%= link_to "Update friendship", edit_user_friendship_path(friendship) %>.
<% end %>
</div>
</div>
<% end %>
Model
class UserFriendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: 'User', foreign_key: 'friend_id'
attr_accessible :user_id, :friend_id, :user, :friend :state
state_machine :state, initial: :pending do
after_transition on: :accept, do: :send_acceptance_email
state :requested
event :accept do
transition any => :accepted
end
end
def self.request(user1, user2)
transaction do
friendship1 = create!(user: user1, friend: user2, state: 'pending')
friendship2 = create!(user: user2, friend: user1, state: 'requested')
friendship1.send_request_email
end

In your index file, you use #user_Friendships which is not the same variable as the one defined in your controller #user_friendship (extra s and capital F).

Related

NoMethodError in RelationshipsController#edit undefined method `decorate' for nil:NilClass

So I know where the problem is, but I'm fairly new to ROR and don't know how to work out what methods are available/which variables I should be using.
What I'm trying to do:
a user should be directed to views/relationship/edit when they press 'edit relationship'.
the variables should correspond so the edit relationship page deals with an accepted, pending or requested relationship between the current_user and the person they're trying to connect to (followed)
if a relationship exists in any state, show the edit button. (works)
click edit button (this is where the error comes up)
show edit page for the relationship between current user and person theyre trying to connect to. (where can accept/delete request)
i don't know why it's saying there is no decorator method - it was working before..
error:
NoMethodError in RelationshipsController#edit
undefined method `decorate' for nil:NilClass
Extracted source (around line #71):
# #relationship = current_user.active_relationships.find(params[:id]).decorate
#followed = User.find_by(name: params[:id])
#relationship = current_user.pending_relationships.find_by(followed_id: #followed).decorate
end
view/users/index:
<% if logged_in? %>
<ul>
<% #users.each do |user| %>
<li>
<%= user.name %>
<div id="relationship-status">
<% if current_user.following.include?(#followed) || current_user.pending_following.include?(user) || current_user.requested_following.include?(user) %>
<%= link_to "Edit Relationship", edit_relationship_path(followed_id: #followed, id: current_user.id), class: "btn btn-primary" %>
followed: <%= #followed %>
current_user: <%= current_user.id %>
relationship: <%= #relationship %>
<% else %>
<%= link_to "Add Relationship", new_relationship_path(follower_id: user.id), class: "btn btn-primary", id: 'add-relationship', data: { followed_id: user.id.to_param } %>
<% end %>
</div>
</li>
<% end %>
</ul>
<% end %>
relationships_controller:
def edit
# #followed = #relationship.followed
# #relationship = current_user.active_relationships.find(params[:id]).decorate
#followed = User.find(name: params[:id])
#relationship = current_user.pending_relationships.find_by(followed_id: #followed).decorate
end
views/relationship/edit:
<div class="page-header">
<h1>Viewing Relationship</h1>
</div>
<h3><%= #relationship.sub_message %></h3>
<div class="form-actions">
<% if #relationship.requested? %>
<%= form_for #relationship, url: accept_relationship_path(#relationship), method: :put do |form| %>
<%= submit_tag "Accept Relationship", class: 'btn btn-primary' %>
<% end %>
<% end %>
</div>
<%= form_for #relationship, url: relationship_path(#relationship), method: :delete do |form| %>
<%= submit_tag "Delete Relationship", class: 'btn btn-danger' %>
<% end %>
model/user:
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
has_many :pending_relationships, class_name: "Relationship",
foreign_key: "follower_id"
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, -> { where(relationships: { state: "accepted" } ) }, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
has_many :pending_following, -> { where(relationships: { state: "pending" } ) }, through: :pending_relationships, source: :followed
has_many :requested_following, -> { where(relationships: { state: "requested" } ) }, through: :pending_relationships, source: :followed
...
# Follows a user.
def follow(other_user)
active_relationships.create(followed_id: other_user.id)
end
# Unfollow a user.
def unfollow(other_user)
active_relationships.find_by(followed_id: other_user.id).destroy
end
# Return true if the current user is following the other user.
def following?(other_user)
following.include?(other_user)
end
def pending_following?(user)
pending_following.include?(user)
end
def requested_following?(user)
pending_following.include?(user)
end
user db table:
relationship controller:
class RelationshipsController < ApplicationController
before_action :logged_in_user, only: [:new, :create, :index, :accept, :edit, :destroy]
respond_to :html, :json
def new
if params[:followed_id]
#followed = User.find(params[:followed_id])
#active_relationship = current_user.active_relationships.new(followed: #followed)
else
flash[:danger] = "Relationship required"
end
rescue ActiveRecord::RecordNotFound
render 'public/404', status: :not_found
end
def create
if params[:relationship] && params[:relationship].has_key?(:followed_id)
#followed = User.find(params[:relationship][:followed_id])
# #followed = User.where(name: params[:relationship][:followed_id]).first
#relationship = Relationship.request(current_user, #followed)
respond_to do |format|
if #relationship.new_record?
format.html do
flash[:danger] = "There was a problem creating that relationship request"
redirect_to followed_path(#followed)
end
format.json { render json: #relationship.to_json, status: :precondition_failed }
else
format.html do
flash[:success] = "Friend request sent"
redirect_to followed_path(#followed)
end
format.json { render json: #relationship.to_json }
end
end
else
flash[:danger] = "Friend Required"
redirect_to users_path
end
end
# def create
# if params[:followed_id]
# #followed = User.find(params[:followed_id])
# current_user.follow(#followed)
# redirect_to user
# else
# flash[:danger] = "else statement"
# end
# end
def accept
#relationship = current_user.active_relationships.find(params[:id])
if #relationship.accept!
flash[:success] = "You are now connected with #{#relationship.followed.name}"
else
flash[:danger] = "That connection could not be accepted."
end
redirect_to relationships_path
end
def index
#relationships = current_user.active_relationships.all
#followed = User.find_by(name: params[:id])
end
def edit
#orig
# #followed = #relationship.followed
# #relationship = current_user.active_relationships.find(params[:id]).decorate
#2nd
# #followed = User.find_by(name: params[:id])
# #relationship = current_user.pending_relationships.find_by(followed_id: #followed).decorate
# stack
# #followed = User.find_by(id: params[:id])
# #relationship = current_user.pending_relationships.find_by(followed_id: #followed).decorate
#stack2
#followed = User.find_by(id: params[:id])
#relationship = current_user.pending_relationships.find_by(follower_id: #followed.id).decorate
end
def destroy
...
end
end
You are finding users by name but passing "ID" for the condition, so it is not able to retrieve corresponding records. Change this and Try Once:
def edit
# #followed = #relationship.followed
# #relationship = current_user.active_relationships.find(params[:id]).decorate
#followed = User.find_by(id: params[:id])
#relationship = current_user.pending_relationships.find_by(follower_id: #followed.id).decorate
end
Update:
You have specified follower_id as foreign key for your pending relationships try the above edit method. I have updated it.
It was saying, with the params[:id] no active_relationships exists for the current user.

undefined method `accepted_user_friendships'

NoMethodError in UserFriendshipsController#index
undefined method `accepted_user_friendships'
I'm getting the above error message when clicking on the 'accepted' link within my index.html page. All the other links function properly except this one. Thanks in advance. Any help is greatly appreciated.
user_friendships_controller
class UserFriendshipsController < ApplicationController
before_filter :authenticate_user!
respond_to :html, :json
def index
#user_Friendships = UserFriendshipDecorator.decorate_collection(friendship_association.all)
respond_with #user_Friendships
end
def accept
#user_friendship = current_user.user_friendships.find(params[:id])
if #user_friendship.accept_mutual_friendship!
#user_friendship.friend.user_friendships.find_by(friend_id: current_user.id).accept_mutual_friendship!
flash[:success] = "You are now friends with #{#user_friendship.friend.name}!"
redirect_to user_friendships_path
else
flash[:error] = "That friendship could not be accepted."
end
end
def block
#user_friendship = current_user.user_friendships.find(params[:id])
if #user_friendship.block!
flash[:success] = "You have blocked #{#user_friendship.friend.name}."
else
flash[:error] = "This friendship could not be blocked."
end
redirect_to user_friendships_path
end
def new
if params[:friend_id]
#friend = User.find(params[:friend_id]).first
raise ActiveRecord::RecordNotFound if #friend.nil?
#user_friendship = current_user.user_friendships.new(friend: #friend)
else
flash[:error] = "Friend required."
end
rescue ActiveRecord::RecordNotFound
render file: 'public/404', status: :not_found
end
def create
if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id)
#friend = User.find(params[:user_friendship][:friend_id])
#user_friendship = UserFriendship.request(current_user, #friend)
respond_to do |format|
if #user_friendship.new_record?
format.html do
flash[:error] = "There was a problem creating this friend request."
redirect_to user_path(#friend)
end
format.json { render json: #user_friendship.to_json, status: :precondition_failed }
else
format.html do
flash[:success] = "Friend request sent."
redirect_to user_path(#friend)
end
format.json { render json: #user_friendship.to_json }
end
end
else
flash[:error] = "Friend required"
redirect_to root_path
end
end
def edit
#friend = User.find(params[:id])
#user_friendship = current_user.user_friendships.find_by(friend_id: #friend.id).decorate
end
def destroy
#user_friendship = current_user.user_friendships.find(params[:id])
if #user_friendship.destroy
flash[:success] = "Your friendship was deleted"
end
redirect_to user_friendships_path
end
def user_friendship
params.require(:user_friendship).permit(:user_id, :friend_id, :user, :friend, :state, :user_friendship)
end
private
def friendship_association
case params[:list]
when nil
current_user.user_friendships
when 'blocked'
current_user.blocked_user_friendships
when 'pending'
current_user.pending_user_friendships
when 'accepted'
current_user.accepted_user_friendships
when 'requested'
current_user.requested_user_friendships
end
end
end
Index.html
<div class="page-header">
<h1> Friends </h1>
</div>
<div>
<strong>Friend list:</strong>
<%= link_to 'Accepted', user_friendships_path(list: 'accepted') %>
<%= link_to 'Pending', user_friendships_path(list: 'pending') %>
<%= link_to 'Requested', user_friendships_path(list: 'requested') %>
<%= link_to 'Blocked', user_friendships_path(list: 'blocked') %>
</div>
<% #user_Friendships.each do |friendship| %>
<% friend = friendship.friend %>
<div id="<%= dom_id(friendship) %>" class="friend row">
<div class="span1">
</div>
<div class="span7">
<strong><%= friend.name %></strong><br />
<%if friendship.pending? %>
<em>Friendship is pending.</em> <%=link_to "Delete request", edit_user_friendship_path(friendship.friend) %>.
<% end %>
<% if friendship.requested? %>
<em>Friendship requested.</em> <%=link_to "Accept Friendship", edit_user_friendship_path(friendship.friend) %>.
<% end %>
<% if friendship.accepted? %>
<em>Friendship started <%= friendship.updated_at %>.</em> <%= link_to "Update friendship", edit_user_friendship_path(friendship.friend) %>.
<% end %>
</div>
</div>
<% end %>
Problem solved. I forgot to add the below code into my user model. That was a complete miss on my part.
has_many :accepted_user_friendships, class_name: 'UserFriendship',
foreign_key: :user_id,
conditions: { state: 'accepted' }
has_many :accepted_friends, through: :pending_user_friendships, source: :friend

How to Cancel Paypal Subscription?

I finally figured out how to implement PayPal Recurring Billing using this tutorial. http://railscasts.com/episodes/289-paypal-recurring-billing
Everything works, But how does one cancel the subscription....
Below is all of the code I've written, and I've also added some comments/questions
ERROR
app/controllers/subscriptions_controller.rb:27:in `show'
Couldn't find Subscription with id=cancel_account
Please help new to rails. :)
CONTROLLER
class SubscriptionsController < ApplicationController
def new
plan = Plan.find(params[:plan_id])
#subscription = plan.subscriptions.build
#subscription.user_id = current_user.id
if params[:PayerID]
#subscription.paypal_customer_token = params[:PayerID]
#subscription.paypal_payment_token = params[:token]
#subscription.email = #subscription.paypal.checkout_details.email
end
end
def create
#subscription = Subscription.new(params[:subscription])
if #subscription.save_with_payment
redirect_to #subscription, :notice => "Thank you for subscribing!"
else
render :new
end
end
def destroy
#subscription = current_user.subscription
#previous_plan = #subscription.plan
if #subscription.cancel_recurring
flash[:success] = 'Subscription Canceled.'
end
redirect_to some_path
end
def paypal_checkout
plan = Plan.find(params[:plan_id])
subscription = plan.subscriptions.build
redirect_to subscription.paypal.checkout_url(
return_url: new_subscription_url(:plan_id => plan.id),
cancel_url: root_url
)
end
end
MODELS
class Subscription < ActiveRecord::Base
attr_accessible :paypal_customer_token, :paypal_recurring_profile_token,
:plan_id, :user_id, :email, :paypal_payment_token
attr_accessor :paypal_payment_token
belongs_to :plan
belongs_to :user
validates_presence_of :plan_id
validates_presence_of :email
validates_presence_of :user_id
def save_with_payment
if valid?
if paypal_payment_token.present?
save_with_paypal_payment
end
end
def paypal
PaypalPayment.new(self)
end
def save_with_paypal_payment
response = paypal.make_recurring
self.paypal_recurring_profile_token = response.profile_id
save!
end
def payment_provided?
paypal_payment_token.present?
end
end
class PaypalPayment
def initialize(subscription)
#subscription = subscription
end
def checkout_details
process :checkout_details
end
def checkout_url(options)
process(:checkout, options).checkout_url
end
def make_recurring
process :request_payment
process :create_recurring_profile, period: :monthly, frequency: 1,
start_at: Time.zone.now + 1.month
end
def cancel_recurring
response = ppr.cancel_subscription(at_date_end: true) #Needs a end period field in
self.current_date_end_at = Time.at(response.current_date_end)
self.plan_id = plan.id
self.status = "canceled"
return self.save
end
private
def process(action, options = {})
options = options.reverse_merge(
token: #subscription.paypal_payment_token,
payer_id: #subscription.paypal_customer_token,
description: #subscription.plan.name,
amount: #subscription.plan.price.to_i,
currency: "USD"
)
response = PayPal::Recurring.new(options).send(action)
raise response.errors.inspect if response.errors.present?
response
end
end
VIEWS
<%= form_for #subscription do |f| %>
<%= f.hidden_field :plan_id %>
<%= f.hidden_field :user_id %>
<%= f.hidden_field :paypal_customer_token %>
<%= f.hidden_field :paypal_payment_token %>
<% unless #subscription.payment_provided? %>
<div class="field">
<%= radio_button_tag :pay_with, :paypal %>
<%= label_tag :pay_with_paypal do %>
<%= image_tag "paypal.png" %>
<% end %>
</div>
<% end %>
*** WHAT WOULD BE THE LINK TO CANCEL THE SUBSCRIPTION ***
<%= link_to image_tag("https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif"),
paypal_checkout_path(plan_id: #subscription.plan_id) %>
<%= link_to "Cancel Subscription", cancel_account_subscriptions_path(plan_id:
#subscription.plan_id) %>
<div id="billing_fields">
<div class="field">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<% if #subscription.payment_provided? %>
Payment has been provided. Click "Subscribe" to complete the subscription.
<% end %>
<div class="actions">
<%= f.submit "Subscribe" %>
</div>
</div>
<% end %>
ROUTES
App::Application.routes.draw do
resources :subscriptions do
collection do
delete :cancel_account
end
end
get 'paypal/checkout', to: 'subscriptions#paypal_checkout'
end
To destroy a users paypal subscription you should create a destroy action in your subscription model.
Subscription_controller.rb
def destroy
#subscription = current_user.subscription
#previous_plan = #subscription.plan
if #subscription.cancel_recurring
flash[:success] = 'Subscription Canceled.'
end
redirect_to some_path
end
In your model get the current user and cancel their subscription. If the user is subscribed monthly but canceled within 2days out of the 30 days, their account subscription should be valid until the at_end_date period(just a heads up).
def cancel_recurring
response = ppr.cancel_subscription(at_date_end: true) #Needs a end period field in
self.current_date_end_at = Time.at(response.current_date_end)
self.plan_id = plan.id
self.status = "canceled"
return self.save
end
Routes.rb
resources :subscriptions do
collection do
delete :cancel_account
end
end
In your view you would iterate through the plans like so
<% #plans.each do |plan| %>
<%= link_to "Cancel Account", cancel_account_subscriptions_path(#subscription, plan_id: plan.id), method: :delete %>
<% end %>

how to setup previous/next message for inbox messaging

I have created a inbox messaging system and it works perfect. However I don't know how to implement a previous and next feature for the messages (so users can go to the next or previous message while viewing one). These are normal functions for viewing messages on the internet. Previous should mean previous by message creation time. Any help would be appreciated.
messages_controller:
before_filter :set_user
def index
if params[:mailbox] == "sent"
#messages = #user.sent_messages
elsif params[:mailbox] == "inbox"
#messages = #user.received_messages
#elsif params[:mailbox] == "archieved"
# #messages = #user.archived_messages
end
if params[:mailbox] == "unread"
#messages = #user.unread_messages
end
end
def new
#message = Message.new
if params[:reply_to]
#reply_to = User.find_by_user_id(params[:reply_to])
unless #reply_to.nil?
#message.recipient_id = #reply_to.user_id
end
end
end
def create
#message = Message.new(params[:message])
#message.sender_id = #user.id
if #message.save
flash[:notice] = "Message has been sent"
redirect_to user_messages_path(current_user, :mailbox=>:inbox)
else
render :action => :new
end
end
def show
#message = Message.find(params[:id])
#message.readingmessage if #message.recipient == current_user
end
def destroy
#message = Message.find(params[:id])
#message.destroy
flash[:notice] = "Successfully deleted message."
redirect_to user_messages_path(#user, #messages)
end
def delete_multiple
if params[:delete]
params[:delete].each { |id|
#message = Message.find(id)
#message.mark_message_deleted(#message.id,#user.id) unless #message.nil?
}
flash[:notice] = "Messages deleted"
end
redirect_to user_messages_path(#user, #messages)
end
private
def set_user
#user = current_user
end
end
message model:
attr_accessible :subject, :body, :sender_id, :recipient_id, :read_at,:sender_deleted,:recipient_deleted
validates_presence_of :subject, :message => "Please enter message title"
belongs_to :sender,
:class_name => 'User',
:foreign_key => 'sender_id'
belongs_to :recipient,
:class_name => 'User',
:foreign_key => 'recipient_id'
# marks a message as deleted by either the sender or the recipient, which ever the user that was passed is.
# When both sender and recipient marks it deleted, it is destroyed.
def mark_message_deleted(id,user_id)
self.sender_deleted = true if self.sender_id == user_id
self.recipient_deleted = true if self.recipient_id == user_id
(self.sender_deleted && self.recipient_deleted) ? self.destroy : self.save!
end
# Read message and if it is read by recipient then mark it is read
def readingmessage
self.read_at ||= Time.now
save
end
# Based on if a message has been read by it's recipient returns true or false.
def read?
self.read_at.nil? ? false : true
end
def self.received_by(user)
where(:recipient_id => user.id)
end
def self.not_recipient_deleted
where("recipient_deleted = ?", false)
end
def self.sent_by(user)
Message.where(:sender_id => user.id)
end
end
show.html (message view):
<strong>From:</strong>
<%= #message.sender %>
</p>
<p>
<strong>Received:</strong>
<%= #message.created_at.to_s(:long) %>
</p>
<p>
<strong>To:</strong>
<%= #message.recipient %>
</p>
<p>
<strong>Message</strong><br />
<%=h #message.body %>
</p>
<p>
<% if #message.recipient == #user %>
<%= link_to "Reply", new_user_message_path(#user, :reply_to => #message.sender) %>
|
<% end %>
<%= link_to "Inbox", user_messages_path(current_user, :mailbox=>:inbox)%>
|
<%= link_to "Delete", [current_user, #message], :confirm => 'Are you sure you want to delete this message?', :method => :delete %>
</p>
In the Message model:
def previous(same_recipient = true)
collection = Message.where('id <> ? AND updated_at > ?', self.id, self.updated_at).order('updated_at ASC')
collection.where(recipient_id: self.recipient_id) if same_recipient
collection.first
end
def next(same_recipient = true)
collection = Message.where('id <> ? AND updated_at < ?', self.id, self.updated_at).order('updated_at DESC')
collection.where(recipient_id: self.recipient_id) if same_recipient
collection.first
end
This is what we use in our Calendar system, very usefull to go Previous / Next with the Apppointments.
This rely on the updated_at column, which is kind of bad (if I update an old message it will confuse the next/previous). Maybe you want to use the created_at column, or your own. With this you could do in your view:
# [...]
<p>
<strong>Message</strong><br />
<%=h #message.body %>
</p>
<p>
<%= link_to 'Next', user_message_path(current_user, #message.next) %>
<%= link_to 'Previous', user_message_path(current_user, #message.previous) %>
</p>
In your controller for the viewing of the message, get 3 messages from the DB, and display the middle entry as the current message. Set the ID's to the previous and next message as variables.
Then in your view make two buttons: previous and next where their link urls are the path to the IDs you saved.

Create method not submitting POST request

I have a controller in a rails app whereby a user can create a holiday request, it seems that when I fill out the necessary information it is not doing the POST request and submitting my form. My output in the RailsPanel follows: Rails Panel. From this its as if it is doing the GET request when surely on it should do a GET then a POST. I believe I have messed up somewhere around my create method. Any feedback would be great thank you!
controller
class HolidaysController < ApplicationController
before_filter :authenticate_user!
before_filter :admin_user, :only => [:index, :update, :edit, :absence]
before_filter :correct_user, :only => [:delete]
def new
#holiday = Holiday.new
#user = current_user
end
def show
#holiday = Holiday.find(params[:id])
c_u = current_user
end
def create
#user = current_user
#holiday = current.holidays.build(params[:holiday])
#holiday.approver_id = approval_method(current_user, #holiday)
if #holiday.save
redirect_to root_path
flash[:success]= "holiday application sent!"
else
render :new
end
end
def myholidays
#holidays = current_user.holidays.all
end
def index
#holidays = Holiday.all
end
def absence
#show the holidays where the approver id matches the current user id
#and state = "requested"'
#user = current_user
if current_user.role? :administrator
# a admin can view all current holiday requests
#holidays = Holiday.all( :conditions => 'state = "requested"')
else
#otherwise an admin sees the holiday requests that they are approvers for
#holidays = Holiday.all(:conditions => ["approver_id = #{current_user.id}", "state = requested"])
end
end
def edit
today = Date.today
#holidays = Holiday.all
#month = (params[:month] || (Time.zone || Time).now.month).to_i
#year = (params[:year] || (Time.zone || Time).now.year).to_i
#shown_month = Date.civil(#year, #month)
#L51 - Parses the given representation of date and time with the given template
#and returns a hash of parsed elements.
#holiday = Holiday.find(params[:id])
end
def update
admin = User.find(current_user.role? :administrator)
holiday = Holiday.find(params[:id])
user = User.find(id = holiday.user_id)
if holiday.update_attributes(params[:holiday])
if holiday.state == "approved"
user.absentdays = user.absentdays - (holiday.days_used).to_i
user.save
end
redirect_to absence_path, :notice => "Request updated"
else
render 'edit'
end
end
def destroy
Holiday.find(params[:id]).destroy
redirect_to root_url, :notice => "Request deleted"
end
private
def current_user?(user)
user == current_user
end
def admin_user
redirect_to dashboard_path, :notice => "You must be an admin to do this!" unless current_user.role? :administrator
end
def signed_in_user
redirect_to login_path, notice: "Please sign in." unless signed_in?
end
def correct_user
#user = current_user
redirect_to dashboard, notice: "You are not the correct user." unless current_user?(#user) or current_user.role? :administrator
end
def approval_method(current_user, holiday_to_approve)
found = false
days = holiday_to_approve.days_used
user = current_user
approver = user.role? :administrator
until found == true
#Admins should be automatically approved and have no approvers
if approver == nil
holiday_to_approve.state = "approved"
#if user absent days is equal to absent days - day and convert to integer
user.absentdays = user.absentdays - (days).to_i
user.save
found = true
else
redirect_to dashboard_path, :notice => "Request complete"
end
break if found == true
end
end
end
holidays/show.html.erb
<form class="form">
<p>You have<b><%= #user.absentdays %> days of holiday left.</b></p>
<%= form_for #holiday do |f| %>
<% if #holiday.errors.any? %>
<div>
<h2>Form is invalid</h2>
<ul>
<% for message in #holiday.error.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
Select the dates required for absence<br>
Start: <%= datepicker_input "holiday", "start_at", :minDate => 0, :dateFormat => "yy-mm-dd" %><br>
End: <%= datepicker_input "holiday", "end_at", :minDate => 0, :dateFormat => "yy-mm-dd" %>
<br><br>
Please select the type of absence you require<br>
<%= f.collection_select :type_id, Type.all, :id, :name, :prompt => "Select absence type" %>
<br><br>
<%= f.text_field :description %>
<br><br>
<%= f.submit "Submit Request", :class => "submit" %>
<% end %>
</form>
new.html.erb
<% provide(:title, 'apply for absence') %>
<p>You have <b><%= #user.absentdays %></b> days of holiday time left.</p>
<%= form_for #holiday do |f| %>
<% if #holiday.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% for message in #holiday.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
Select the dates required for absence<br>
start: <%= datepicker_input "holiday","start_at", :minDate => 0, :dateFormat => "yy-mm-dd" %><br>
end: <%= datepicker_input "holiday","end_at", :minDate => 0, :dateFormat => "yy-mm-dd" %>
<br><br>
Please select the type of absence you require<br>
<%= f.collection_select :type_id, Type.all, :id, :name, :prompt => "Select absence type" %>
<br><br>
Please provide a short description of the nature of your absence (if applicable)<br>
<%= f.text_field :description %>
<br><br>
<%= f.submit "submit" %>
<% end %>
</div>
The reason is, you are having a form in your holidays/show.html.erb but not in your holidays/new.html.erb.
According to rails convention, if form is submitted in new.html.erb, then by default the POST method is called of that particular controller.
But since your file is show.html.erb, you have to explicitly define your POST method in the form_for.
form_for #holiday , :url => { :action => :create }, :html => { :method => "post"} do |f|

Resources