I've got three classes Admin, Client, Agent which all inherit from User < ActiveRecord::Base. The system is designed using STI, hence all classes share the same users table.
I am interested in keeping the CRUD functionality pretty much the same, hence for now I am using a single UsersController.
When implementing the Update functionality I'm faced with a doubt.
Here's my edit form:
#Edit Form
<%= form_for(#user,{url:user_path(#user),method: :put}) do |f| %>
<%= render 'edit_fields',f:f %>
<%= f.submit "Save", class: "btn btn-large btn-primary"%>
<% end %>
#UsersController
def edit
#user=User.find(params[:id])
end
def update
binding.pry
#if #user.update_attributes(params[:user]) #<---BEFORE
#WORKAROUND BELOW
if #user.update_attributes(params[#user.type.downcase.to_sym])
flash[:success]="User was updated successfully."
redirect_to user_path(#user)
else
flash[:danger]="User could not be updated."
render 'new'
end
end
My "problem" is that params is dependent on the #user.type of the #user instance. Therefore sometimes there's a params[:client], other times a params[:admin] or params[:agent].
Hence the line
if #user.update_attributes(params[:user]) does not always work.
The workaround I implemented works fine, but I was wondering whether there's a more DRY or elegant way to approach these issues, i.e. sharing CRUD between different STI-ed classes.
There is indeed a much more elegant solution. Just change your form_for declaration and add the as option, like this:
<%= form_for(#user, as: :user, url: user_path(#user), method: :put) do |f| %>
That way in your controller your parameters will be scoped under the user key instead of the model's class.
In your controller, check for the User type in a before_filter as below. I've used this for similar STI Controllers and works great for me.
before_filter :get_user_type
private
def get_user_type
#klass = params[:type].blank? ? User : params[:type].constantize
end
And then for example you could call a show method as :
def show
#user = #klass.find params[:id]
#render
end
Using #klass across your CRUD actions should simplify your Controller.
Related
I have post which belongs_to users, and would like an option when editing to be able to change the user that post is associated with.
I've made a start, but I am very new to Rails and a bit stuck.
I started in my post_controller.rb.
def update
#post.user = associated_user
if #post.update(post_params)
flash[:notice] = "Post was successfully updated"
redirect_to edit_post_path(#post)
else
render 'edit'
end
end
I've defined the method associated_user in my application_controller.rb (I want to do this for a more than just articles.)
def associated_user
#associated_user ||= User.find(session[:user_id]) if session[:user_id]
end
I understand that this code is wrong - I don't want it to get the logged in user, I want to get it from the field I've set in my form view.
<%= f.text_field :associated_user, class: "form-control", placeholder: "Edit Author" %>
Ideally this form field would be a drop down listing all users with a certain status (a boolean I have already set in the users table.)
I'm not sure how far away I am, but if any one is able to offer some guidance, that would be greatly appreciated!
How are the relationships defined in the models. If your post belongs to users, then use a dropdown control in your form:
f.collection_select :user_id, User.whateverscope, :id, :text_method
and when the form is submitted rails will do the rest.
If you have something different set up, then post your models, your strong_params methods, etc.
I am trying to figure out the best way to do the following (there are a few ways I can think of, but I want to know what the best way to handle it is):
A user is putting together a shipment, and then clicks the "Send" link, which sends him to the /shipments/:id/confirm page. The confirm action checks to see if the user has a completed ShippingAddress; if not, it sends him to the ShippingAddress#new. (If he does, it render the confirm page.
I want the user to be able to complete the ShippingAddress#new page, submit it, and then be redirect back to the /shipments/:id/confirm. How can I do that? How can I pass the :id to the ShippingAddress#new page without doing something like redirect_to new_shipping_address_path(shipment_id: #shipment.id) in the Shipment#confirm action? Or is that the best way to do that?
class ShipmentsController < ApplicationController
def confirm
#shipment = Shipment.where(id: params[:id]).first
unless current_user.has_a_shipping_address?
# Trying to avoid having a query string, but right now would do the below:
# in reality, there's a bit more logic in my controller, handling the cases
# where i should redirect to the CardProfiles instead, or where I don't pass the
# shipment_id, and instead use the default shipment.
redirect_to new_shipping_address_path(shipment_id: #shipment.id)
end
end
end
class ShippingAddressesController < ApplicationController
def new
#shipment = Shipment.where(id: params[:shipment_id]).first
end
def create
#shipment = Shipment.where(id: params[:shipment_id]).first
redirect_to confirm_shipment_path(#shipment)
end
end
[In reality, there is also a CardProfiles#new page that needs to be filled out after the shipping address is].
Try calling render instead of redirect_to, and set the id into an instance variable. Adjust the view logic to pull that instance variable if it exists.
#shipment_id = #shipment.id
render new_shipping_address_path
In the view
<%= form_for #shipment_address do |f| %>
<% if #shipment_id %>
<%= hidden_field_tag :shipment_id, #shipment_id %>
<% end %>
I don't know your view logic entirely, but giving an example.
I have this form in my application.html.erb.
<%= form_tag(:action=>"index", :controller=>"posts") %>
<p>
// code here
</p>
I dont understand why is this getting directed to posts->create instead of posts->index?
Thanks.
Basically, Rails observes and obeys "RESTful" web service architecture. With REST and Rails, there are seven different ways to interact with a server regarding a resource. With your current code, specifying the form's action as index doesn't make sense: Rails' form helpers can either POST, PUT or DELETE.
If you wanted to create a post, then redirect to the index, you can do so in the applicable controller action:
class PostsController < ApplicationController
...
def create
#post = Post.new
respond_to do |format|
if #post.save
format.html { redirect_to(:action => 'index') }
end
end
While your form would look like:
<% form_for #post do |f| %>
# put whatever fields necessary to create the post here
<% end %>
You seem to be a little mixed up with respect to the uses for each action. Here's a quick summary of typical RESTful usage:
Index -> view a list of items
New/Edit -> form where items are added or edited
Create/update -> controller action where items are created/updated
The reason your routes file is not taking you to index is because index is not an action where posts are typically created or updated. The best way is to go RESTful. Unless you have a very unusual situation, the best way to set your system up is probably a little like this:
# routes.rb
resources :posts
# application.html.erb (or better: posts/_form.html.erb).
<% form_for #post do |f| %>
<% end %>
# posts controller, whichever action you want to use
def new
#post = Post.new
end
By putting the form in a partial called form you can access it in new, edit, or wherever else you need to manipulate a post in your system.
Ok, I have search Google, API's as well as StackOverflow and have found no real decisive help for my issue. So here goes!
I have a Polymorphic model setup named Favorite and it ties to the User. Being that Favorite is Polymorphic I of course can use the relationship to allow my user to add pretty much any entity in my application as their Favorite.
Each of these Favorite relationships between the user and a specific model I want to be able to call different things such as 'Favorite' or 'Like' or 'Friends'. This allows me to have a different Controller with Views to manage each of these different relationships so they are more understandable to the user and myself. Hence I am covering the global generic idea of Favorites with a more precise idea of a 'Friend'.
So I went ahead and created a Friend controller with its associated views to handle the Favorite relationship between a user and other user's in the system.
But what I have found is that Rails expects me to pass a 'Friend' model in all of my interactions between views and controller even though I want to use the Favorite model and I get 'uninitialized constant Friend' as an error in my view. How do I get past this 'convention', how do I make the controller and views if necessary understand that I am using the Favorite model as my underlying model not the Friend?
I considered creating a new model named 'Friend' and inheriting it from 'Favorite' just to fool the controller, but man that just seems like a waste of energy to me. Any ideas out there?
CODE EXAMPLE this is using the Favorite polymorphic model to ButtSlap another User. Each form partial is pass the User as a local variable called local_entity.
ButtSlapController
class ButtSlapsController < AuthorizedResourceController
def create
#favorite = current_user.favorites.build(params[:favorite])
respond_to do |format|
if #favorite.save
flash[:success] = 'butt slap successful!'
format.html { redirect_to('/lounge') }
# format.js { render :action => "create_success"}
else
flash[:success] = 'ah poop!'
format.html { redirect_to('/lounge') }
# format.js { render :action => "create_failure"}
end
end
end
def destroy
#favorite = current_user.favorites.find(params[:id])
respond_to do |format|
if #favorite.destroy
flash[:success] = 'butt slap has been successfully removed.'
format.html { redirect_to('/lounge') }
# format.js { render :action => "create_success"}
else
flash[:success] = 'ah poop!'
format.html { redirect_to('/lounge') }
# format.js { render :action => "create_failure"}
end
end
end
end
Creates The ButtSlap
<%= form_for current_user.favorites.build, :as => :favorite, :url => butt_slaps_path do |f| %>
<div><%= f.hidden_field :favorable_id, :value => local_entity.id %></div>
<div><%= f.hidden_field :favorable_type, :value => local_entity.class.to_s %></div>
<div class="actions"><%= f.submit "butt slap!" %></div>
<% end %>
Removes the ButtSlap
<%= form_for current_user.get_favorites(
{:id => local_entity.id,
:type => local_entity.class.to_s}),
:html => { :method => :delete }, :url => butt_slaps_path do |f| %>
<div class="actions"><%= f.submit "take back" %></div>
<% end %>
Well it all turned out to be a little gem called CanCan v1.6.4
I have been using CanCan for Authorization within my application and when declaring your authorization rules in your Ability class you can either do it by Model or by Controller or a mixture.
In order to handle this I setup 2 root Controllers which inherited from ApplicationController. The first 'AuthorizedController' is used for all controllers which do not use a Model and the second 'AuthorizedResourceController' is used for all controllers which are backed by a Model.
Turns out that for my ButtSlap controller I had it setup as an AuthorizedResourceController and by doing so CanCan was automatically looking to pull and authorize either a collection or a single model based off of the controller's name 'ButtSlap'. But due to the fact that I was using the Favorite model on the backend every time I tried to post to the controller CanCan tried to load its imaginary model based off of its convention. And I thus received the errors messages 'Uninitialized Constant 'ModelName''.
Once I switched the ButtSlapController from an AuthorizedResourceController over to a AuthorizedController CanCan no longer looked to instantiate and authorize a model based off the controller name and it moved to controller based authorization instead and just like everyone was saying 'Poof' my confusion as to why Rails was looking for a Model tied to a controller name was gone.
You really have to love bugs like this, they really stretch your limits as well as your keyboard stockpile (I tend to throw keyboards when I get frustrated ;)
One thing you can do on my rap lyric explanation site is "like" explanations (once you're logged in):
http://dl.getdropbox.com/u/2792776/screenshots/2010-01-17_1645.png
I'd like to show the "Like" links to users who aren't logged in, and then, when a non-logged in user clicks "Like", show him a lightbox with a "Login or Register" form (like Digg / Reddit)
http://dl.getdropbox.com/u/2792776/screenshots/2010-01-17_1650.png
What's the best way to accomplish this?
Currently I'm using this approach:
Clicking "Like" POSTs to /annotations/:id/vote (the POST body indicates whether the user is liking or "unliking").
The vote Annotation controller action has a require_user before_filter that looks like this:
def require_user
unless current_user
store_desired_location
flash[:notice] = "You'll need to login or register to do that"
redirect_to login_path # map.login '/login', :controller => 'user_sessions', :action => 'new'
return false
end
end
user_sessions#new looks like this:
def new
#user_session = UserSession.new
respond_to do |format|
format.html {}
format.js {
render :layout => false
}
end
end
The problem is that the redirect doesn't seem to work correctly over javascript:
http://dl.getdropbox.com/u/2792776/screenshots/2010-01-17_1700.png
How do I get this to redirect correctly?
Also, is this the right general approach? Another thought I had was to attach a different handler to the "Like" links in javascript when there was no logged in user (but I don't think this method scales well to other actions that I'd like to handle the same way)
There's a few problems to overcome here.
Browsers in general do not allow redirecting to a POST request.
redirect_to doesn't preserve format without additional input.
Store location does not preserve form data.
All these problems can be solved by eliminating redirects.
Here is how I've handed it in the past:
Instead of redirecting in required_user, render. If a before filter redirects or renders the pending action is cancelled. (No need to return false either). Unfortunately going this route blurs controller boundaries. But allows for simple html fallback, and lends its self to DRYness.
The high level view of the new work flow will be:
Request to annotations#vote (POST)
required_user filter fails
render new session
submit login information and original POST data back to annotations#vote (POST)
new filter in vote captures session information and logs in. vote proceeds as expected. If login fails return to 3.
annotations#vote redirects/renders as it should
Start by reworking the require_user to render the user_sessions#new template.
def require_user
unless current_user
flash[:notice] = "You'll need to login or register to do that"
#user_session ||= UserSession.new
respond_to do |format|
format.html {render :template => 'user_sessions/new'}
format.js {
render :template => 'user_sessions/new', :layout => false
}
end
end
end
The #user_session ||= UserSession.new ensures we can return validation errors to the form.
Now we've got to beef up your user_session#new template so that it can remember the action. Also if you plan on using lightboxes, this should be a partial rendered rendered by relevant RJS or the new.html.erb.
First we create a partial to create hidden fields preserving the POST data that would have been lost in a redirect:
<% if params[:controller] == "annotations" %>
<% content_for :old_form do %>
<%= hidden_field_tag "annotation[song_id]", params[:annotation][:song_id] %>
<%= hidden_field_tag "annotation[vote]", params[:annotation][:vote] %>
<% end %>
<% end %>
Then render that partial in the login partial that will occupy your lightbox:
<%= render :partial => vote_form_replica %>
<% url = params[:controller] == "user_sessions ? user_sessions_url : {} %>
<% form_tag #user_session, :url => url do |f| %>
<%= yield :old_form %>
<%= f.label :user_name %>
<%= f.text_field :user_name %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= submit_tag %>
<%end%>
The empty hash for url in the form_tag looks like an error, but isn't. It ensures that the form data is posted to the url that rendered the form. Which at this point should be annotations/:id/vote
Now for the new filter to login. Essentially it will be doing what ever UserSessionsController#create does without the render/redirect. The following is copied from the RESTful authentication plugin.
def authenticate
self.current_user = User.authenticate(params[:login], params[:password])
if logged_in?
if params[:remember_me] == "1"
current_user.remember_me unless current_user.remember_token?
cookies[:auth_token] = { :value => self.current_user.remember_token,
:expires => self.current_user.remember_token_expires_at }
end
end
end
All that's left is to make sure the filter order is right.
before_filter :authenticate, :require_user, :only => :vote
N.B.: You're probably not going to use this version of require_user without this version of authenticate so it makes sense to combine them into a single filter.
And that's it. The way this has been set up allows for robust DRY easily reuseable code. By placing the new filters into ApplicationController they're available in any controller. From this point, adding this functionality to any other controllers/actions takes only 3 simple steps:
Create a new partial modelled after the vote_form_replica partial.
Add the corresponding render statement to the new session template.
Apply the filters to your actions.
I would approach this in the way you describe at the bottom of your question. Before displaying the page initially, check if the user is logged in. If they are, the "Like" links should use their normal behavior. If not, bind a click event to show the register/login panel. There's nothing about this that can't be reused. In fact, we use this exact method at my job. Any user action that requires authentication either follows its normal behavior or pops up a generic login panel depending on login state at the time the page loads.