【问题标题】:rails 3, How to set and pass a query string through an Controller#create action that doesn't saverails 3,如何通过不保存的 Controller#create 操作设置和传递查询字符串
【发布时间】:2011-12-30 16:42:30
【问题描述】:

我有 3 个用户按顺序看到的视图,首先他们选择一个位置,然后选择一个类别,然后他们被发送到一个表单。第一个视图将位置信息发送到类别选择视图。在类别选择视图中,我使用查询字符串将类别 ID 发送到表单。在 Controller#new 操作中,我将查询字符串放入实例变量中:@award = Award.find(params[:award])

问题在于,如果用户没有填写适当的字段,则表单不会保存,查询字符串将不再存在。在我的情况下,这意味着推荐不再具有类别,这将继续使表单失败。

如何通过失败的创建操作保留查询字符串?

def create
    @recommendation = Recommendation.new(params[:recommendation])
    @recommendation.user_id = current_user.id


    respond_to do |format|
      if @recommendation.save
        format.html { redirect_to location_path, notice: 'Recommendation was successfully created.' }
        format.json { render json: @recommendation, status: :created, location: @recommendation }
      else
        format.html { render action: "new" }
        format.json { render json: @recommendation.errors, status: :unprocessable_entity }
      end
    end
  end

编辑 _

我想我可以将新操作分享给:

def new
    @recommendation = Recommendation.new
    @award = Award.find(params[:award])
    @recommendation.approvals.build
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @recommendation }
    end
  end

【问题讨论】:

  • 您可以随时将数据“保留”在表单的隐藏字段中
  • 我的视图包含一个隐藏字段,但隐藏字段由实例变量填充,该变量在保存失败后返回 nill。
  • @TJ Sherrill 我假设您有一个填充表单的推荐对象以及该表单上对应于 Recommendation.category 的隐藏字段(并且您在最初呈现表单时设置了它的值) .如果提交该表单并失败,您希望您的控制器操作使用推荐对象的数据重新呈现该表单;您在其中存储了该类别值。这没有发生?如果您没有 category 作为推荐对象的属性 - 请务必通过 attr_accessor 或通过迁移将其添加为 db 列。
  • 奖项和类别是一个 HABTM,所以两者都有很多,所以我不能简单地添加 attr_accessor,对吧?

标签: ruby-on-rails ruby-on-rails-3 query-string


【解决方案1】:

好吧,由于查询字符串已经从新操作传递到创建操作,如果创建操作失败,它将命中您的 'format.html { render action: "new" }' 行。

你可以这样做:

format.html {redirect_to thing_path(@thing, :foo => params[:foo])}

【讨论】:

  • 我必须提供 redirect_to new_recommendation_path(:award => @award) 来返回它找不到奖励...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多