I have two controllers for two respective models, by example, photos and categories. index and show methods are very similar in each controller, and the views are identical. What is the best method for share the view by the two models?
I've though two options:
Use a helper. In the helper will put the code for the view, and will call the helper from each view (photos/views and categories/views)
Use a partial in each views. I think it's a more clean solution, but I see huge DRY's in my mind when going to code this solution.
So, I have two controllers from two models, each one at and exposes a #photo object (photos controller with all the photos, and categories controller with just the selected categorie's photos) and I need one view to show both.
I'm looking for an elegant solution for this, complaining REST and DRY principes. Any idea?
Thanks in advance.
I have a similar situation with one of my projects. All the delete views for most controllers are styled the same way, display the same confirmation boxes, and simply renders a predictable display of whatever object is being deleted.
The solution was quite simple and elegant in my opinion. Simply put, what we (the developers) did was create a new directory in app/views called shared and put shared views in there. These could be full template files or just partials.
I would suggest using a shared template (in neither categories nor photos view directories, but rather in the shared directory) and rendering it manually from the view.
e.g. have a method as such in both controllers and a file app/views/shared/photo.html.erb:
def show
#photo = Photo.first # ... or whatever here
render :template => 'shared/photo'
end
This should successfully render the shared template. It is the DRYest route and doesn't have the feeling of pollution you get when using a more-or-less empty view in each controller's view directory just to include a shared partial, as I understand your question is suggesting.
About the first answer:
If the partial must be rendered from a view:
<%= render :partial => "shared/photo" %>
and the partial must be in app/views/shared/_photo.html.erb
I'd use an helper because they are shared among views. For the HTML part, I'd use partials so it would be a mix of both ways.
This looks like a good use case for the Cells gem.
#bjeanes If all your delete views are the same, you can create views/default/delete.html.erb and all the delete actions will use it.
That's what i'm doing: Most of my views are on default, and i create specific ones only when needed
Update: Ok, this post is from 2009, anyway, i will keep my comment here in case someone gets here from Google like i did.
Related
I have two controllers, UsersController and TransactionsController and I'm wondering what the best practices is for displaying data from both controllers on one view. Should I create partials under each corresponding views directory and then stitch them together in a separate view or do I create one view under layouts? Am I way off?
EDIT:
In my Views folder:
devise
(devise default views are in here)
layouts
_header.html.erb
application.html.erb
transactions
_form.html.erb
index.html.erb
delete.html.erb
edit.html.erb
new.html.erb
users
index.html.erb
I want to show both all users in one table and their transactions in another on the root page.
If transactions belong to user, you should be able to access transaction data on the user page by default (if models&migrations are set up correctly). If your users index.html.erb will be your root page, that should solve your problem.
If you are trying to show this data in an administration page for example then your code should go like this
Controllers:
admin_controller.rb -> with action users_transactions
views/admin
users_transactions.html.erb -> loop on users showing the partial of user
views/transcations
_user_transactions.html.erb
views/users
_user.html.erb -> here you will show how a single user will show including the partial of his transactions.
So I guess it all depends on 'what' you want to display and 'how'.
Leave the views/layouts Dir for what it was created, storing layouts. Generally cross-view partials are kept in the views/shared Dir, which stores partials that could be rendered from another directories. in your case form transactions/* & users/*.
Plan wisely before adding a file there... maybe you don't really need it ;)
I'm trying to implement the following behavior:
You can see that i have pretty standart views structure for controller, but instead "actions" partial, i created folder which is named like an action and in them i have a partials for actions.
I Try use "prepend_view_path":
def set_view_paths
self.prepend_view_path ["#{Rails.root}/app/views/#{controller_name}/#{action_name}"]
end
But rails finds next:
Missing template "posts/index"
in ".../app/views/posts/index"
I need to add somthing like that in the end of the action:
render template: 'index'
Question:
Is there a more beautiful way to solve this problem?
Checkout this SO thread. From reading the thread it doesn't look like there is a clean way for you to solve this problem. The only way would be to override render.
I'm not sure why you are putting your template files into subfolders but, if it is not providing you with any benifit, it's probably easier to move index.html.erb, show.html.erb ect out of their subfolders and just put them under views/posts.
This will also make it easier for other developers (and yourself, later on) because you are conforming to Rails conventions.
I'm writing a web app containing posts and comments. Since there are many places I need to display a bunch of posts with their comments, I'm thinking about reusing the code. But I'm not sure if it is correct to use a partial _posts.html.erb that displays each post in #posts, or implement it directly through the show action in posts controller, and render this action when necessary in other views. Anyone has any idea?
For this use case, partials are your best bet.
As you said, there are many places I need to display a bunch of posts with their comments. A main premise of Rails is Don't Repeat Yourself. It is far more tidy (and programmatically sound) to retrieve #posts in your various controller actions and then render those posts/comments using partials in your views. Otherwise, you'd be rendering the show action within other views – views aren't really meant to render out actions, but the other way around, rather.
Yes, according to DRY principle your are thinking in a perfect manner, you should create a partial.
A good practice is instead of using #posts, you should pass posts as a locals like:
<%= render 'posts', posts: #posts %>
in this way you can use this partial from anywhere with providing just posts as locals without any dependency on #posts instance variable.
In my current project I have a couple instances where I have a re-usable form that exists inside a rails partial. This form submits to a specific controller via ajax (:remote => true). The controller does some stuff and then returns back the appropriate js.erb to modify the page via javascript.
This works fine for when I have a single view. But the problem seems to happen when this re-usable partial exists on multiple views. In view 1 I might want to issue a completely different set of javascript commands then in view 2.
As a concrete example, say I have a comments controller that has the normal CRUD operations.
I now have partial called _comments_box.erb. This _comments_box.erb contains the ability to submit a comment via a simple line:
- form_for comment, :url => post_comments_path(post), :remote => true do |f|
This submits to a comments_controller.rb create method which looks somethings like this:
def create
... do some stuff, like create a new comments model
respond_to do |format|
# will respond with create.js.erb
format.js
end
end
The create.js.erb in turn adds a comment to the view, perhaps doing a bunch of other updates to the DOM.
Say I render the _comments_box.erb within a view called post_summary.erb. Now I have another view, post_detail.erb that requires the same _comments_box.erb. However the post_detail.erb requires me to update completely different divs on the DOM in response to a new comment.
I need to create a different JS response for each instantiation. So I can either:
Create an alternate controller method, say create_2. Pass in some parameter to the _comments_box.erb from post_detail.erb to the _comments_box.erb partial so it knows which controller method to fire. This will allow me to have a separate file _create_2.js.erb that will allow me to manipulate the post_detail.erb view independently.
Forget about using js.erb altogether and just use plain old AJAX and get back JSON, and handle the javascript manipulation completely on the client-side.
It seems option 1 allows me to continue to use the UJS supported by Rails which is nice. But also means I probably will be adding a lot of duplicate code everywhere which is annoying. Is there a way for me to do this elegantly while continuing to use UJS?
That's exactly the purpose of Apotomo: http://apotomo.de/
Here is it's own description:
Apotomo is a true MVC widget framework
for Rails. Widgets are based on Cells
and provide reuseable view components.
Having bubbling events, they know when
and how to update themselves via AJAX!
Working with Apotomo widgets almost
feels like developing GUI components –
in a Rails environment.
Have a try, it's great.
I'd not recommend using UJS for frontend apps: server shouldn't take care of client side business. I agree it's useful and clean but it lacks performance and thus should be kept for backend stuff (RJS will move into a gem, see here: http://weblog.rubyonrails.org/2011/4/21/jquery-new-default).
That said, back to the solutions you expose:
1) I think you won't need an extra controller, you'd just have to pass additional params in order to know from where to query came from. A hidden_field could do the trick. With this info, render the good js.erb file
format.js { if condition
render "create.js.erb"
else
render "create_2.js.erb"
end
}
2) I'd go for it and return json but you'll face the same problem: knowing from where the request comes from.
A better solution (than using a hidden_field) might be to check the request.referer in your controller action. This way you leverage the fact that each context has a unique URL, and don't have to explicitly specify another unique value when rendering your widget partial.
I decided to try to use the cells plugin from rails:
http://cells.rubyforge.org/community.html
given that I'm new to Ruby and very used to thinking in terms of components. Since I'm developing the app piecemeal and then putting it together piece by piece, it makes sense to think in terms of components.
So, I've been able to get cells working properly inside a single view, which calls a partial. Now, what I would like to be able to do (however, maybe my instincts need to be redirected to be more "Rails-y"), is call a single cell controller and use the parameters to render one output vs. another.
Basically, if there were a controller like:
def index
params[:responsetype]
end
def processListResponse
end
def processSearchResponse
end
And I have two different controller methods that I want to respond to based on the params response type, where I have a single template on the front end and want the inner "component" to render differently depending on what type of request is made. That allows me to reuse the same front-end code.
I suppose I could do this with an ajax call instead and just have it rerender the component on the front end, but it would be nice to have the option to do it either way and to understand how to architect Rails a bit better in the process.
It seems like there should be a "render" option from within the cells framework to render to a certain controller or view, but it's not working like I expect and I don't know if I'm even in the ballpark.
Thanks!
How would the cell know in which controller it is rendered? This would break encapsulation.
You can use #render_cell in your controller view and maybe put some decider around it? Is that what you're asking for?