Wednesday, 15 August 2012

Rails 4 passing variables in the views or templates -



Rails 4 passing variables in the views or templates -

i have app allow owner (but not public users) upload photo album files , photos. when coding views, noticed strange.in block in albums/index.html.erb file, if pass in variable @album.id, nomethoderror nilclass.yet, if remove "@", (or remove variable entirely), works fine.

but in albums/show.html.erb file, in link_to line of code editing album title, need "@album.id" passed (or variable left out entirely) in order work.

why that?

here albums/index.html.erb file , code

<div class="admin_login"><%= link_to "admin login", new_album_path %></div> <div class="home"><%= link_to "home", root_path %></div> <h1>albums gallery</h1> <% @albums.each |album| %> <div> <%= link_to album.name, album_path(album.id) %> </div> <% end %>

and here albums/show.html.erb file:

<h3><%= link_to @album.name %></h3> <div class="album"> <%= link_to "edit", edit_album_path(@album.id) %> <%= link_to "delete", @album, method: :delete, data:{confirm: "are sure want delete album? photos in permanently deleted!"} %> </div> <br><%= link_to "back", albums_path %>

for clarity, here albums controller code:

class albumscontroller < applicationcontroller def index @albums = album.all end def new @album = album.new end def create @album = album.new(album_params) @album.save redirect_to albums_path end def show @album = album.find(params[:id]) end def edit @album = album.find(params[:id]) end def update @album = album.find(params[:id]) if @album.update(album_params) redirect_to album_path(@album.id) else render 'edit' end end def destroy @album = album.find(params[:id]) @album.destroy redirect_to albums_path end private def album_params params.require(:album).permit(:id, :name, :category) end end

in index action, you're defining series of albums @albums. in show action, define single @album. these variables accessible in action in defined.

the reason 'album' works in index view each block defining local 'album' variable within block's scope.

<% @albums.each |album| %> <div> <%= link_to album.name, album_path(album.id) %> </div> <% end %>

that |album| after block says "for iteration, assign current value variable album"

ruby-on-rails variables ruby-on-rails-4 views

No comments:

Post a Comment