I've been stumped as to why my rails app is rendering the wrong partial. I have two partials, each related to a different controller (invitations and guests controllers). One partial lists the number of invitations sent out to users and the second partial lists those users who have confirmed their invitation. In addition, the second partial also allows one to see a simple profile of the confirmed guests.
What is happening is that when I visit the link related to the guests controller events/1/guests/, I expect to see the partial related to the guest profile. Instead, the partial related to the invitations controller is rendered. Both the invitations and guests controllers are nested resources of events.
Below is the code that I have been working with. Thanks!
Routes
resources :events, only: [:new, :show, :create] do
resources :invitations, only: [:new, :create, :show]
resources :guests, only: :show
end
match '/events/:id/guests', to: 'guests#show'
Guests controller
def show
#event = Event.find_by_id(params[:id])
#guestlist = #event.invitations.where(accepted: true)
end
views/guests/show.html.erb
<% provide(:title, #event.eventname + " Guest List") %>
<h1> Guest list for <%= #event.eventname %> </h1>
<% if #event.invitations.any? %>
<%= render #guestlist %>
<% end %>
views/guests/_guestlist.html.erb
<li>
<%= guestlist.name %> | <%= guestlist.occupation %> |
<%= guestlist.interests %>
</li>
Instead, the following partial is being rendered:
views/invitations/_invitation.html.erb
<li>
<%= invitation.name %> | <%= invitation.email %> |
<% if invitation.accepted == true %> <%= "Confirmed" %> <% else %> <%= "Pending" %> <% end %>
</li>
The following snippet depicts the correct way to invoke your partial:
# app/views/guests/show.html.erb
<%= render :partial => 'guests/guestlist', :locals => {:guestlist => #guestlist} %>
Since you need access to the #guestlist instance variable in your partial, you'll need to pass it as a local. Then, in your partial, guestlist will be available as a local variable.
Then, within your partial, you'll need to iterate over the members of your guestlist:
# app/views/guests/_guestlist.html.erb
<% guestlist.each do |guest| %>
<li>
<%= guest.name %> | <%= guest.occupation %> | <%= guest.interests %>
</li>
<% end %>
UPDATE:
The reason the OP's original invocation of the partial rendered the invitation partial is that #guestlist is actually comprised of Invitation objects, and thus, the <%= render #guestlist %> method was actually looking for a partial named invitation. From the canonical Rails guides:
There is also a shorthand for this. Assuming #products is a collection
of product instances, you can simply write this in the index.html.erb
to produce the same result:
<h1>Products</h1>
<%= render #products %>
Rails determines the name of the partial to use by looking at the
model name in the collection.
Because of this, you need to explicitly declare the name of the partial you want to use, otherwise ActionView will use the invitation partial by default.
If #guestlist is an object of type Guest, then it would by default render _guest.html.erb.
So, you can try This
<%= render 'guestlist' %>
Variable #guestlist would be automatically available in the partial, so no need to pass it in locals.
Hope this works.
In your show action, you have defined
#guestlist = #event.invitations.where(accepted: true) # it returns array of obejects or records
Now, Please have a try with the following code
views/guests/show.html.erb
<% unless #guestlist.blank? %>
<%= render "/guests/guestlist" %>
<% end %>
views/guests/_guestlist.html.erb
<% #guestlist.each do |guestlist| %>
<li>
<%= guestlist.name %> | <%= guestlist.occupation %> |
<%= guestlist.interests %>
</li>
<% end %>
Related
I'm new in ruby on rails, and I want to practice it.
I'm stuck when I want to include a view into antoher view.
I want by doing that to have my posts into another view than of posts/index
posts/index
method:
def index
#Posts = Post.all
end
view:
<% #posts = capture do %>
<% #posts.each do |post| %>
<h3>
<%= post.title %>
</h3>
<p>
<%= post.content %>
</p>
<% end %>
<% end %>
pages/index
<h1> Index Of another pages </h1>
<%= #posts %>
If you want to force your index action to render another view, then go with follow code:
def index
#Posts = Post.all
render 'pages/index'
end
Correct me if I haven't get you
It sounds to me like you need to save the reusable view code as a partial, and render it all places it's required.
To use a partial, save it down with an underscore prefix, i.e. _posts.html.erb.
This can then be rendered using:
<%= render 'path/to/posts' %>
You'll likely need to pass in the posts variable to the partial, as in the following:
<%= render 'path/to/posts', posts: #posts %>
And the change your view to use posts rather than #posts.
Update:
The result of capture is assigned to #posts, although this variable still wouldn't be available in another template - rather to be used again on the same page
Based on what you're saying about the project's structure, it sounds like you'd need the following:
in app/views/posts/_posts.html.web
<% #posts.each do |post| %>
<h3>
<%= post.title %>
</h3>
<p>
<%= post.content %>
</p>
<% end %>
In both controllers' index action:
#posts = Post.all
In the posts/index view:
<%= render 'posts' %>
In the pages/index view:
<%= render 'posts/posts' %>
I don't want to confuse things, but Rails has a little magic in there where -
alternatively - you can define a partial _post.html.erb as follows:
<h3>
<%= post.title %>
</h3>
<p>
<%= post.content %>
</p>
And simply call <%= render #posts %> in each view. This would be the best 'Railsy' way of doing things.
Let me know how you get on!
Rails cancancan how to limit user privilige in view when there are lots of roles? And each role has multiple priviliges.
For example, in my rails app there are about 50 view files, such as article.html.erb, product.html.erb, comment.html.erb, order.html.erb,...,and so on. What I have to do is adding priviliges in every .html.erb file:
<% if can? :update, #article %>
<%= link_to "Edit", edit_article_path(#article) %>
<% end %>
...
<% if can? :update, #product %>
<%= link_to "Edit", edit_product_path(#product) %>
<% end %>
So if in this way, I have to do a lot of tedious works. When the requestment is changed, I have to modify multiple .html.erb files.
So my question is, if there is any methods that I can accept to avoid this way? Such as using a global tag to control all the views to display or not display the "Edit","Destroy" methods?
You can use layouts in rails.
Create a partial view, say _user_privileges.html.erb inside layouts folder in app/views and write the code related to privileges there. Now in each of the other view files you can use <%= render 'layouts/user_privileges' %>. So now you can use a single file to change the privileges.
_user_privileges.html.erb
<% if can? :update, #article %>
<%= link_to "Edit", edit_article_path(#article) %>
<% end %>
...
<% if can? :update, #product %>
<%= link_to "Edit", edit_product_path(#product) %>
<% end %>
article.html.erb, product.html.erb, comment.html.erb, order.html.erb etc.
...
<%= render 'layouts/user_privileges' %>
...
I have a classes User and Company, I want to re-use the users partial as the to render company staff.
In my CompaniesController I have:
def staff
#company=Company.find(params[:id])
#users=#company.works_fors.paginate(page: params[:page], :per_page => 10)
#title=#company.name+" staff."
end
And in my staff.html.erb template I have:
<% if #users.any? %>
<ul class="users follow">
<%= render #users %>
</ul>
<%= will_paginate %>
<% end %>
This is the works_fors/_works_for partial:
<%= render :partial => 'user' %>
Which Renders
<li>
<%= gravatar_for user, size: 50 %>
<%= link_to user.name, user %>
<% if current_user.developer? && !current_user?(user) %>
| <%= link_to "delete", user, method: :delete,
data: { confirm: "You sure?" } %>
<% end %>
</li>
However this throws an error on the user object as it cant find the method
undefined local variable or method `user' for~~
I think this is because Im calling the user object from within companies but there is a defined relationship, or do I need to redefine in companies ?
It's hard to tell, but it appears that what you call #users in your controller is in fact not a User collection, but a WorkFor collection.
#users = #company.works_fors...
What you mean is:
#works_fors = #company.works_fors...
This means that staff.html.erb is working with a works_for collection. So you should rename the variable in your template to avoid confusion.
# staff.html.erb
<% if #works_fors.any? %>
<ul class="users follow">
<%= render #works_fors %>
</ul>
<%= will_paginate #works_fors %>
<% end %>
Now we know we are rendering a works_for partial. So an instance of works_for is be available inside the partial. We need to ask it for its associated user instance, and pass it to the render method.
# works_fors/_works_for.html.erb
<%= render works_for.user %>
As a bonus, you can save yourself some queries by preloading the users.
#works_fors = #company.works_fors.includes(:user)...
I've got this working now quite accidentally, but I don't understand what causes it to break when I explicitly specify what partials are to be used for rendering the resource/s. Can anyone explain it?
The index template for my Posts controller contained the following line, which was giving me an error:
<%= render partial: 'posts', collection: #posts %>
The error (in my browser) said:
NoMethodError in Posts#index
Showing /Users/applebum/Sites/rails_projects/eventful2/app/views/posts/_posts.html.erb where line #1 raised:
undefined method `any?' for #<Post:0x000001064b21f0>
Extracted source (around line #1):
1: <% if posts.any? %>
2: <div id="posts">
3: <% posts.each do |post| %>
4: <%= render partial: "posts/post", locals: { post: post } %>
Changing the problem line to
<%= render #posts %>
made the error disappear and the posts appear (displayed nicely in markup from the appropriate partials) as I had wanted and expected them to.
Here's my _posts.html.erb partial:
<% if posts.any? %>
<div id="posts">
<% posts.each do |post| %>
<%= render partial: "posts/post", locals: { post: post } %>
<% # render :partial => "comments/comments", :collection => post.comments %>
<% end %>
</div>
<% end %>
And the _post.html.erb partial it's referring to, if that matters:
<div class="post" id="post_<%= "#{post.id}" %>">
<div class="post_inner">
<%= link_to avatar_for(post.user, size: "small"), post.user.profile %>
<div class="post_body">
<div class="user-tools">
<% if can? :destroy, post %>
<%= link_to '<i class="fi-x"></i>'.html_safe, post, :method => :delete, remote: true, :class => "delete", :confirm => "Are you sure you want to delete this post?", :title => post.content %>
<% end %>
</div>
<h5 class="username">
<%= link_to post.user.name, post.user.profile %>
<span class="timestamp">• <%= time_ago_in_words(post.created_at) %> ago</span>
</h5>
<div class="content">
<%= post.content %>
</div>
<ul class="foot">
<li>Like<li>
<li>Share</li>
</ul>
</div>
</div>
</div>
And the relevant bits from the controller:
class PostsController < ApplicationController
respond_to :html, :js # Allow for AJAX requests as well as HTML ones.
before_filter :load_postable
load_and_authorize_resource
def index
#post = Post.new
#posts = #postable.posts
end
private #################
def load_postable
klass = [User, Event].detect { |c| params["#{c.name.underscore}_id"] } # Look for which one of these there's a ***_id parameter name for
#postable = klass.find(params["#{klass.name.underscore}_id"]) # Call find on that, passing in that parameter. eg Event.find(1)
end
Can anyone explain to me what's going on here? I couldn't find anything in the Layouts and Rendering guide at rubyonrails.org.
Thanks!
Your error comes from assuming :collection and #posts mean the same thing when rendering. From Rails Docs (point 3.4.5):
Partials are very useful in rendering collections. When you pass a collection to a partial via the :collection option, the partial will be inserted once for each member in the collection
So, if you use that, for each post, you will be doing post.any? which fails as any? isn't defined for a single post.
From the same docs, you should check if render returns Nil to see if the collection is empty:
<h1>Posts</h1>
<%= render(#posts) || "There are no posts." %>
PD: Use the partial to render only one post, not all of them.
GL & HF.
At the moment I try to do following:
I created several partials (i.e. _show_signature.html.erb) for my user.
Now I want to show them on clicking a link.
In my user controller, I created a new action:
def show_signature
#is_on_show_signature = true
end
def show_information
#is_on_show_information = true
end
on my user show.html.erb i coded this:
<% if #is_on_show_information %>
<%= render :partial => 'show_information' %>
<% elsif #is_on_show_signature %>
<%= render :partial => 'show_signature' %>
<% end %>
and in my "navigationbar" i wrote:
<ul>
<li class="profile-tab">
<%= link_to 'Information', show_information_path %>
</li>
<li class="profile-tab">
<%= link_to 'Signature', show_signature_path %>
</li>
</ul>
In my routes.rb I wrote:
map.show_information '/user-information', :controller => 'user', :action => 'show_information'
map.show_signature '/user-signature', :controller => 'user', :action => 'show_signature'
now my problem:
clicking on my "information" link will redirect me to http://localhost:3000/user-information (cause I told him this path in routes.rb - I think) and I get an error:
uninitialized constant UserController
But that's not what I want... My user show path is something like:
http://localhost:3000/users/2-loginname
(by coding
def to_param
"#{id}-#{login.downcase.gsub(/[^[:alnum:]]/,'-')}".gsub(/-{2,}/,'-')
end
in my user model)
I want to link to somethink like http://localhost:3000/users/2-test/user-information.
Any ideas how it will work? Any ideas why I get this error?
As far as Rails conventions go, the model itself is singular (User) but the table (users) and controller (UsersController) are both pluralized. This can cause a significant amount of confusion at first, and even after years of working with Rails I still make the mistake of trying things like 'user = Users.first' which is, of course, not valid, as often you get to thinking about table names instead of class names.
Also, for toggling the display of elements on a page, you probably want to use the link_to_remote method which uses AJAX for updates instead of a page refresh. If you're okay with a full page refresh, those actions will need to redirect_to something, such as the page referrer, or you will get a blank page or error since the page template does not exist.
Typically what you do is:
<ul>
<li class="profile-tab">
<%= link_to_remote 'Information', show_information_path %>
</li>
<li class="profile-tab">
<%= link_to_remote 'Signature', show_signature_path %>
</li>
</ul>
Then each action is as you have specified, however, the page template show_information.rjs would look like:
page.replace_html('extra_information', :partial => 'show_information')
Keep in mind you will need to have a placeholder to receive the partial contents, so simply wrap your optional sections in an element with a specific ID:
<div id="extra_information">
<% if #is_on_show_information %>
<%= render :partial => 'show_information' %>
<% elsif #is_on_show_signature %>
<%= render :partial => 'show_signature' %>
<% end %>
</div>