0

My client has asked for a single url to complete a workflow in their application: example.org/task/:token. Where :token is a unique id for that task.

Within the TaskController in the index action :token is used to query the task object and the view is rendered based upon the Task's current state:

def index
  @task = Task.where(token: params[:token])
  render @task.state.to_s
end

Every state has a view and the logic for rendering the view is in the view itself (UGLY!!).

I'd like to refactor this so that Task state is used to determine which controller action to render. I can do that with render template: '#{state}/action'. But this doesn't execute the controller action logic. Meaning I'm still stuck with controller logic in the view!

I've found this solution that works, but it's a bit ugly and breaks some of rails "magic" (have to explicitly render the view.)

My questions is, is there a better way to accomplish this within Rails while still maintaining the single url and not redirecting to a new url?

4

2 に答える 2

1

受け入れられなかった回答にリンクしました。そのリンクで受け入れられた回答をお勧めします ( https://stackoverflow.com/a/6051812/1461068 )

具体的には、この部分:

def your_action
  ...
  render :action => :index
end

次のように処理できます。

def index
  @task = Task.where(token: params[:token]).first
  render :action => get_action_for_state(@task.state.to_s)
end

private

def get_action_for_state(state)
    //logic to figure out which action to call
end
于 2013-03-20T18:21:37.697 に答える
0

これを見てください: http://railscasts.com/episodes/217-multistep-forms ryanb には良いアイデアがあると思います。基本的に、タスクの状態に応じて、 task.html.erb に適切なパーシャルをレンダリングさせます。

  <%= render "#{@task.state}_state", :f => f %>
于 2013-03-20T18:16:29.923 に答える