ruby-on-rails - Rails- Controller :notice - Add a variable?

标签 ruby-on-rails ruby controller scaffolding

我是新手,但有一个关于修改脚手架的 :notice 以添加变量的基本问题。例如,rails 为我创建了以下创建方法:

 def create
    @order = Order.new(params[:order])

    respond_to do |format|
      if @order.save
        format.html { redirect_to(@order, :notice => 'Order was successfully created.') }
        format.xml  { render :xml => @order, :status => :created, :location => @order }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @order.errors, :status => :unprocessable_entity }
      end
    end
  end

我想要做的是向 :notice 添加一个变量,以便它可以具体打印创建的订单(或使用 update 方法编辑的订单)。我尝试了一些基本的操作,例如传递 <%= order.id %>,但我觉得这在 Controller 中似乎不自然?

是否可以在此脚手架的这种格式中添加动态值?还是违背惯例。

非常感谢您的帮助,如果这是非常新的内容,我们深表歉意。

最佳答案

Beestings 是在 ruby​​ 中将动态值插入字符串的首选方式。所以如果你想在你的 :notice 中使用 @order.id,你可以这样做:

 def create
    @order = Order.new(params[:order])

    respond_to do |format|
      if @order.save
        format.html { redirect_to(@order, :notice => "Order id # #{@order.id} was successfully created.") }
        format.xml  { render :xml => @order, :status => :created, :location => @order }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @order.errors, :status => :unprocessable_entity }
      end
    end
  end

关于ruby-on-rails - Rails- Controller :notice - Add a variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4222040/

相关文章:

java - Spring Boot Controller 未被映射

ruby-on-rails - 我可以在 Ruby on Rails 中将 api Controller 用于其他 Controller 吗

ruby-on-rails - Ruby on Rails 自引用创建操作返回未知属性错误

ruby-on-rails - ruby instance_variable_get 返回 nil

ruby - ruby 的数据库抽象/适配器

ruby - 从ruby中的初始化调用方法时未定义的方法

api - 如何将字符串转换为 time.Time

ruby-on-rails - Rails/AJAX部分渲染

ruby-on-rails - Rails - 捕获 'Invalid Authenticity Token' 异常

ruby-on-rails - 尝试在测试中运行 rails c 时获取 config.eager_load 设置为 nil