在Rails 4 App中按ID查找对象

时间:2015-02-13 15:20:48

标签: ruby-on-rails wicked-gem

我使用Wicked在我的rails 4应用中构建了一个向导。我特意跟着this guide,唯一的区别是我用嵌套资源做这件事。我的控制器操作有困难,应该找到表单使用其ID建立的对象。

应用程序的当前流程是用户单击创建对象的按钮,并重定向到向导的第一步,该步骤在一系列步骤中更新对象。问题是我没有通过参数传递对象的ID,因为我在ID字段中传递了向导的步骤。

创建对象的按钮

<%= link_to business_loan_application_path(@user), method: :post, :class => "btn btn-success" do %><% end
%>

LoanApplication Controller

    def create
      @user = current_user
      @loanapplication = @user.loan_applications.new
      @loanapplication.save(validate: false)
      redirect_to business_loan_application_wizard_path(@user.id,LoanApplication.form_steps.first)
    end  

我需要以某种方式将:loan_application_id传递给business_loan_application_wizard_path参数。

错误

Couldn't find LoanApplication without an ID

LoanApplication belongs_to Business through has_many relationship。

{"business_id"=>"55", "id"=>"business_details"}

business_details是向导的第一步。这些是我通过带有put请求的按钮首次创建对象时传递的参数。

向导控制器

class WizardController < ApplicationController
  include Wicked::Wizard
  before_filter :authenticate_user!
  before_filter :require_business

  steps *LoanApplication.form_steps

  def show
    @business = current_user
    @loanapplication = LoanApplication.find(params[:loan_application_id])
    render_wizard
  end

  def update
    @business = current_user
    @loanapplication = @business.loan_applications.last
    @loanapplication.update_attributes(loan_application_params(step))
    render_wizard @loanapplication
  end
end

1 个答案:

答案 0 :(得分:0)

this question中的讨论有助于解决这个问题。

已更改

resources :wizard

scope "loan_application/:loan_application_id" do
  resources :wizard
end

在我的routes.rb文件中。

我的向导控制器现在如下:

def show
  @business = current_user
  @loanapplication = LoanApplication.find(params[:loan_application_id])
  render_wizard
end

def update
  @business = current_user
  @loanapplication = LoanApplication.find(params[:loan_application_id])
  @loanapplication.update_attributes(loan_application_params(step))
  render_wizard @loanapplication
end

最后,贷款申请控制器重定向链接已更改:

def create
  @user = current_user
  @loanapplication = @user.loan_applications.new
  @loanapplication.save(validate: false)
  redirect_to business_loan_application_wizard_path(@user.id, LoanApplication.form_steps.first, :loan_application_id => @loanapplication.id) 
end