I am in the process of Drying up my Rails 4 app. I have noticed that I type out the exact same code quite a lot and that it might be better to place this in a concern. I am just not exactly sure how to do this, as I suspect it might require some Meta Code.
I would like to place (ex.) this "create" method in a controller concern called CrudGenerator:
def create
if #contact_us.validate(params[:contact_us])
#contact_us.save
flash[:success] = t :create_success_flash, class_object: "Contact Us"
respond_with(#contact_us, :location => new_contact_path)
else
render :new
end
end
Now this will nee to accept 2 params if moved to a concern i.e. "contact_us" and "new_contact_path" as these params will be unique each time this concern is included. These are the only sections of this code that will change.
I have tried to use define_method to generate the below code, but I am not 100% certain.
Any advice on how to generate the below code in a concern and make it part of my ContactUsController ?
Thanks
You can move the code in a concern like this:
def create
resource_class.new(permitted_resource_params)
if resource.save
redirect_to some_path
else
render :new
end
end
And then include this concern in the controllers you want to add this functionality to. To load the resource, you can do it in a before_action call and load resource using params[:controller_name].capitalize.constantize... I hope you get the point
Related
I'm trying to build a profile page that displays posts sent only to the requested user, and allows the visitor to write a post of their own. Because this simplified example should have two distinct controllers: users and posts, I made partials for each post action to render within the user's show action.
Directory structure for my views directory looks like this:
- posts
- _index.html.erb
- _new.html.erb
- users
- show.html.erb
... (etc.)
Section that displays these partials within the user's show.html.erb:
<section>
<h3>Posts:</h3>
<%= render '/posts/new', :post => Post.new %>
<%= render '/posts/index', :posts => Post.where(target_id: params[:id]) %>
</section>
I eventually found out that you could pass variables into the partial in this render line, and though this works, it's very messy and probably doesn't follow the best practices.
Ideally, I'd want these partials to be connected with the posts controller so I can write more complex database queries in a place that isn't the view:
class PostsController < ApplicationController
def new
#post = Post.new
end
def index
#posts = Post.where(target_id: params[:id])
end
def create
#post = Post.new(post_params)
#post.user_id = current_user.id
#post.target_id = params[:post][:target_id]
if #post.save
redirect_to :back, notice: 'You published a post!'
else
render new
end
end
private
def post_params
params.require(:post).permit(:body)
end
end
Currently, I haven't found a way of doing this. I know this is a newb question, but thanks for any help in advance.
You are attempting to treat your controllers like models: doing the post work in post controller and the user work in user controller. But controllers are task-oriented, not model-oriented.
Since you want posts info in your user form, it's typical to gather it in the user controller. E.g.
class UsersController < ApplicationController
def show
...
#posts = Post.where(user_id: user.id)
end
end
That #posts instance variable is visible in the show template and any partials it calls. But many coders prefer to send it explicitly through render arguments, as more functional:
<%= render '/posts/post_list', posts: #posts %>
For one thing it's easier to refactor when you can see at a glance all of the partial's dependencies.
I agree somewhat with #Mori's advice. As he said, you are trying to put too much logic into the controller. I think this was a result of you trying to get it out of the view, which is the right idea, but you want business logic to be in the model.
Also, those index and new actions for PostsController are never going to be called. When you are calling the render posts/new for example, that is rendering the view, not the controller action. So, those controller actions have no reason to exist.
I would implement the fix in perhaps a different way than Mori described. It's a recommended practice to try and pass as few instance variables from the controller to the view as possible (see 3rd bullet in the linked section).
Since it's really the show action of the UsersController we are talking about here, I as someone trying to understand your code would assume the instance variable you are passing to the show view is something like #user.
You may want to use an includes method when instantiating the #user object. The includes statement will allow you to load the additional models you will need to instantiate using the minimum number of queries possible (preventing an N+1 query situation). You probably don't want to load every single one if there are thousands of matching posts, so I put an arbitrary limit of 10 on that.
UsersController
def show
#user = User.find(params[:id]).includes(:received_posts).limit(10)
end
#....
View
<section>
<h3>Posts:</h3>
<% unless #user.id == current_user.id %>
<%= render 'posts/form', post: Post.new(user_id: #user.id) %>
<% end %>
<%= render #user.received_posts %>
</section>
Putting the partial for a new post instead as a view called posts/form will allow you to reuse that form if you want to render an edit action (form_for knows which action to use on submit by calling the passed model's persisted? method).
Note that this code assumes the User model has the second relationship with posts set up to be called received_posts, but you can change it to whatever reflects the reality. By passing the received_posts collection to the render method, Rails is smart enough to know that if you want to render a collection of Post models to look for a posts/_post partial and render one for each Post. It's a little cleaner looking IMO. Just make sure to move your posts/show code into that. posts/show implies this is its own action and not something used as a partial for something else.
I have a rails app where many of the models are editable using best_in_place, so I have a lot of controllers that look partially like this:
before_action :find_objects, except: [:new, :create]
def update
#object.update_attributes(object_params)
respond_to do |format|
format.json { respond_with_bip #object}
end
end
private
def object_params
params.require(:object).permit(:foo, :bar)
end
def find_objects
#object = Object.find(params[:id])
end
How do I move this particular repeated piece into a controller concern, given that the object being updated is going to come in with a particular name in the params hash, and object_params and find_objects should call their proper versions based on the model name? Is there some elegant meta-magic that'll sort this all out?
I think this is a case where your code could be "too DRY". You can certainly accomplish this using meta-magic, but it could make your code confusing in the long run.
If you want to do the meta-magic, one trick is to use params[:controller] to get the name of the model. For example, if you have a PostsController, then:
params[:controller] # => "posts"
params[:controller].classify # => "Post"
Taking this a step further, you could write a generic find_object like this:
def find_object
model_class = params[:controller].classify.constantize
model_instance = model_class.find(params[:id])
instance_variable_set("##{model_class.name.underscore}", model_instance)
end
But as I said at the beginning, I'm not sure I would recommend this amount of abstraction just for the sake of DRY-ing your controller code.
In my Rails app I have an invoices_controller.rb with these actions:
def new
#invoice = current_user.invoices.build(:project_id => params[:project_id])
#invoice.build_item(current_user)
#invoice.set_number(current_user)
end
def create
#invoice = current_user.invoices.build(params[:invoice])
if #invoice.save
flash[:success] = "Invoice created."
redirect_to edit_invoice_path(#invoice)
else
render :new
end
end
Essentially, the new method instantiates a new invoice record plus one associated item record.
Now, what sort of method do I need if I want to duplicate an existing invoice?
I am a big fan of Rails's RESTful approach, so I wonder if I should add a new method like
def duplicate
end
or if I can use the existing new method and pass in the values of the invoice to be duplicated there?
What is the best approach and what might that method look like?
Naturally, you can extend RESTful routes and controllers.
To be rally RESTful, it is important to look exactly, what you want.
i.e. if you want a new invoice and use an existing one as a kind of template, then it is comparable to a new action, and the verb should be GET (get the input form). As is it based on an existing invoice, it should reference that object. After that you would create the new invoice in the usual way.
So in you routes:
resources :invoices do
member do
get 'duplicate'
end
end
giving you a route duplicate_invoice GET /invoices/:id/duplicate(.format) invoices#duplicate
So in your view you can say
<%= link_to 'duplicate this', duplicate_invoice_path(#invoice) %>
and in your controller
def duplicate
template = Invoice.find(params[:id])
#invoice= template.duplicate # define in Invoice.duplicate how to create a dup
render action: 'new'
end
If I understand correctly your question you can:
resources :invoices do
collection do
get 'duplicate'
end
end
and with this you can do:
def duplicate
# #invoice = [get the invoice]
#invoice.clone_invoice
render 'edit' # or 'new', depends on your needs
end
clone_invoice could be a custom method which should have a invoice.clone call in your custom method.
If you question if you can use additional methods except REST, you absolutely can. Google, for example, encourage developers to use something, what they call "extended RESTful" on GoogleIO, http://www.youtube.com/watch?v=nyu5ZxGUfgs
So use additional method duplicate, but don't forget about "Thin controllers, fat models" approach to incapsulate your duplicating logic inside model.
Given a rails RESTful controller
class WidgetsController
def new
#widget = Widget.new
end
def create
#widget = Widget.new(params[:widget])
render :new and return unless w.save
redirect_to widget_path(#widget)
end
end
Other than to capture the parameters and render validation messages why is the convention to render :new instead of redirect_to new_widget_path if validation fails?
As URL will alter from /widgets/new to /widgets if validation fails doesn't this break the concept of REST?
Render will not call the controller action, so the instance variables that you have set in the create action will be taken to the new view.
this means that any validation errors persist in the new view...
redirect_to would run the controller action for new, and therefore create a new instance of your model... and you would loose the errors...
hope this helps
Could you do this instead of rendering the new action?
flash[:thing] = params[:thing]
redirect_to new_thing_path
Then in new
#thing = Thing.new(flash[:thing] || params[:thing])
This honestly seems nicer to me because otherwise if you have any logic in your controller that is required to render the new/edit actions, you have to repeat that logic (or create some before_filter or something) in update/create. I realize this involves one more request but aside from that it seems simple and safer to code (apart from the fact that you are breaking rails conventions) and it gives the user a valid url that is always the same for looking at/doing the same thing.
If they refresh they'll lose their values but that is true of any form before being submitted. And that seems to make more sense to me than refreshing resulting in a resubmit warning which is pretty strange. How is a user supposed to clear the form for example?
This rails-ism has always bugged me. Are there are any serious issues with this that I'm not considering? Do other application frameworks all do the same?
The thing with render is that it will not cause another request to be generated. It will go to the corresponding view and display it. With redirect, however, a redirect request to the browser will be generated, which will cause another request to your server.
I'd like to create a before_filter method in my application controller like this...
def check_role(role_name)
unless logged_in_user.has_role? role_name
flash[:notice] = 'Access to that area requires additional privileges.'
redirect_to :back
end
end
However, it doesn't look as though before filters can take parameters.
Is there a way to parameterize this call, or am I trying to drive a screw with a hammer?
You should be able to do this with a block:
before_filter {|controller| controller.check_role('admin') }
You can use a bit of meta-programming. Something like this (completely untested, just something to give you an idea of how it might go):
Module RoleWithIt
Role.all.each do |role|
define_method("check_#{role.name}_role".to_sym) do
check_role(role.name)
end
end
def check_role(role_name)
return if logged_in_user.has_role?(role_name)
flash[:notice] = 'Access to that area requires additional privileges.'
redirect_to :back
end
end
ApplicationController.send :include, RoleWithIt
To have it load when your app initialises, just put it in a file called role_with_it.rb and put it in your lib directory.
am I trying to drive a screw with a
hammer?
Er, possibly ;-)
If I'm reading this correctly, you have a situation where actions within a controller have different access levels, so you want to remove the duplication by creating a single check function?
So you're looking to do something like this?
before_filter :check_role('admin'), :only => [:admin, :debug]
before_filter :check_role('power'), :only => [:edit, :delete]
But the parameter in parens thing is not legal. And anyway, I still see a fair bit of duplication here!
In general, with an area of functionality as well-visited as controller filters, if you can't do something, it's probably because you're looking at something the wrong way. (Remember that Rails is proud to describe itself as "opinionated software"!)
How would it be if you were able to know the action name in your filter method?
Then we'd have
before_filter :check_role
Which is pretty DRY.
We could define permissions in a Hash, perhaps:
Perms = { :admin => ['admin'], :edit => ['admin', 'power'], etc
... which seem to encapsulate the distinct elements of the duplication. If it got complex then the whole thing could move off into a table, although then you're probably duplicating functionality already available in a plugin.
And we'd have
protected
def check_role
for required_role in Perms[params[:action]]
return if logged_in_user.has_role? required_role
end
flash[:notice] = 'Access to that area requires additional privileges.'
redirect_to :back
end
Or something similar. params[:action] works on my current Rails version (2.1.2), although the Rails book (v2) mentions an action_name method that seems to return blank for me.
I don't believe you can pass parameters to filters. So what I have do in the past is made static methods that pass the parameter to the method that needs the params.
So I would have something like this:
def check_role(role_name)
unless logged_in_user.has_role? role_name
flash[:notice] = 'Access to that area requires additional privileges.'
redirect_to :back
end
end
def check_admin_role
check_role('admin')
end
def check_blah_role
check_role('blah')
end
Then in your controller you'd just call
before_filter :check_admin_role
There is probably some way to implement this with meta-programming but I am still quite a n00b and haven't figured that part out yet ;)
it's an old question, but if somebody still wonders, a good asnwer for rails 4 can be found here