Reputation: 31
I have been breaking my head for 3 hours now and I can't figure this out, I recently started working with Rails and I'm in love with it, but there's still some little things I don't know. Like I have a view that pulls all the data from a table.
<% @albums.each do |album| %>
<div class="album">
<%= album.artist %> - <%= album.album %>
</div>
<div class="albumTask">
<%= link_to 'Show', album %>
<% if can? :update, @album %>
<%= link_to 'Edit', edit_album_path(album) %>
<% end %>
<% if can? :destroy, @albumy %>
<%= link_to 'Destroy', album, confirm: 'Are you sure?', method: :delete %>
<% end %>
</div>
<% end %>
But what I really want it to do is to only pull the data where genre = Dubstep. Now in PHP I would do something like.
$result = mysql_query("SELECT * FROM albums WHERE genre='dubstep'")
What am I missing?
Upvotes: 0
Views: 71
Reputation: 19249
I think what's important for you is understanding how the MVC (model-view-controller) architecture works. Here's a link on how it works.
The code you provided is your view, and it knows how to display a list of albums. But it's the controller that does most of the job in MVC, such as giving a list of albums to your view. Now currently, if it wants to index all the albums, it calls this part in your /app/controllers/AlbumsController.rb
:
def index
@albums = Album.all
respond_to [...]
[...]
end
This is where the @albums.do each {...}
in your view comes from. What I would do is similar, but instead of .all
, pass a .where(:genre => :params[:genre])
clause instead, where the parameter comes from your url.
Upvotes: 0
Reputation: 12322
If you use ActiveRecord, just add where clause to the query:
Album.where(:genre => "dubstep")
Some additional info: http://guides.rubyonrails.org/active_record_querying.html#conditions
Upvotes: 1