【问题标题】:Redirecting to BarsController#create from FoosController#create从 FoosController#create 重定向到 BarsController#create
【发布时间】:2017-02-11 06:30:57
【问题描述】:

我在 another answer 中读到,redirect_to 不同控制器的 create 操作是不好的做法。

我正在尝试在Foos#new 上的表单中实现Create Foo and Bar 按钮。

Foo 使用表单中的信息,Bar 可以使用Foo 的 id 到Foo.find(params[:foo_id])Foo 获取所需的信息。对我来说,我应该这样做是有道理的:

if params['route_to']['bar']
  redirect_to controller: :bars, action: :create, foo_id: @foo.id
else
  redirect_to foos_path
end

在我的Foos#create 末尾。

  • 我是否犯了架构错误?
  • 有什么更好的方法?
  • 如何将redirect_to 告诉POST 而不是GET?因为现在我要提交GET,而我想要POST
  • 我应该使用concerns吗?

【问题讨论】:

    标签: ruby-on-rails forms http ruby-on-rails-4 model-view-controller


    【解决方案1】:

    如果我理解正确,您想在创建 Foo 对象后创建 Bar 对象吗?我只是在 Foo 的 create 方法中这样做。

    类似

    def create
        @foo = Foo.new(foo_params)
        if @foo.save
          @bar = Bar.new
          @bar.attribute1 = @foo.attribute_bar_needs
          @bar.save
        end
    end
    

    更好的是,如果需要在每个 Foo 对象之后创建一个 bar 对象,那么我会在 Foo 模型中创建一个 after_create 回调来这样做,而不是在控制器中这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多