Reputation: 17
I am new to Rails and I am working on a simple application for "tasklist" (To do list).
In my app, I want to categories the tasks based different type of category(shopping, todo - user can create own category). So I created separate model for User
, Category
and Task
and each Task
is linked with one category
.
In my view (users/show.html.erb
-n side this I render view for category
and task
), I have listed all the categories in left side and all the open tasks in right side. I want to make categories as LINKS, so when user select one categories, only the tasks which is linked to that category type will get displayed in the right side.
I understand how a normal link_to works when it takes to a new page. I also understand how button works in bootstrap. But I am not able to identify how I can pass the category selection into the controller, so I can pull only the task where the category matches with what user selected.
Thanks for the help.
Upvotes: 0
Views: 1745
Reputation: 76784
You need to pass the category
parameter to some sort of evaluation function, filtering the appropriate categories. This can either be done with Javascript
or Rails
:
Rails
<% Category.all.each do |category| %>
<%= link_to category.name, users_path(user, category: category.id) %>
<% end %>
This will pass a category
param to your users#show
action:
def show
@user = User.find params[:id]
@categories = @user.categories
@categories = @categories.where(category: params[:category]) if params[:category]
end
Javascript
If you wanted to be explorative, you'd want to use JS to keep your functionality on this view only:
#app/assets/javascripts/application.js
$(document).on("click", "a.category", function(e){
var id = $(this).data("category_id");
$(".todos a").not("[data-category_id=\"" + id + \""]").hide();
});
#app/views/users/show.html.erb
<% Category.all.each do |category| %>
<%= link_to category.name, users_path(user, category: category.id), class: "category", data: { category_id: category.id } %>
<% end %>
<div class="todos">
<% @user.todos.each do |todo| %>
<%= link_to todo.title, todo, data: { category_id: todo.category_id } %>
<% end %>
</div>
This will allow you to click a "category" and have the list of "todos" change to suit.
Upvotes: 0
Reputation: 1747
May be you should create a new route instead of passing parameter.
resources(:categories) do
member do
get(:linked_tasks)
end
end
And in categories controller
def linked_tasks
category = Category.find(params[:id])
tasks = category.tasks.where(is_linked: true)
end
Hope this will help you.
Upvotes: 0
Reputation: 34336
You can pass the category
in your link_to
like this:
link_to "Task for test_category", task_path(category: "test_category")
Then, you can grab the category using params[:category]
inside your controller and use it according to your need.
Upvotes: 0