Вопрос

I've got routes that look like this:

resources :projects do
  resources :tasks
end

Which gives you a URL like so: URL/projects/14/tasks/3

The models define that:

project has_many :tasks
task belongs_to :project

Right now, when a user clicks on the link to a task, I'm loading the tasks#show into a div via a remote => true link from within a project's show view. This is working fine.

#tasks/show.js.erb

$('#task_content').html("<%= j render(partial: 'tasks/single', locals: { t: @task }) %>");

#tasks/_single.html.erb

<%= t.content %>

The problem is that I want the user to be able to visit URL/projects/14/tasks/3 and have the task load into the the div on the project view automatically.

Basically, I need to find a way to have URL/projects/14/tasks/3 actually render URL/projects/14, and call a jquery $('a#task_<%= task.id %>').click()

I can't seem to figure out how to go about getting the view to recognize this kind of behavior. Can anybody point me in the right direction?

Thanks!!!

EDIT

#TasksController
  def show
    @task = Task.find(params[:id])
    respond_to do |format|
      format.js
    end
  end


#ProjectsController
  def show
    @project = Project.find(params[:id])
    respond_to do |format|
      format.html # show.html.erb
    end
  end

Projects#show has two main elements:

  1. Links with an id of task_<%= task.id %>
  2. The div that the task content should be loaded into (div#task_content)
Это было полезно?

Решение

Basically, I need to find a way to have URL/projects/14/tasks/3 actually render URL/projects/14, and call a jquery $('a#task_<%= task.id %>').click()

You can test if the task was reached by a standard HTTP call (non AJAX), and redirect to the project's url, passing in a parameter to autoload the task on load. Since your default case uses a js format, it's even simpler - you can just test for an html format:

#TasksController
def show
  @task = Task.find(params[:id])
  respond_to do |format|
    format.html { redirect_to project_path(@task.project_id, :load_task_id => @task.id) }
    format.js
  end
end

# somewhere in /projects/show partial
<% if params[:load_task_id] %>
  <script type="text/javascript">
    $(function(){
      $('a#task_<%= params[:load_task_id] %>').click()
    });
  </script>
<% end %>

Другие советы

I would probably use Rails Routing Constraints to direct xhr requests to the tasks controller and send http requests to the projects controller with the task ID as a param, make that a variable available to your view, then your view can check if a the task variable exists and load the div? Or inspect the URL with JS, perhaps.

Something along the lines of:

match "/projects/:id/tasks/:tid", :to => "projects#show", :constraints => lambda { |request| !request.xhr? }
match "/projects/:id/tasks/:tid", :to => "tasks#show", :constraints => lambda { |request| request.xhr? }

Untested but might werk?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top