作为请求我编辑,包括attr_accessor
Rails的方式。我只是飞过去,希望你能得到它。你肯定需要阅读更多关于轨道及其概念的介绍。
你有轨的模型,让我们把它叫做动物
class Animal < ActiveRecord::Base
attr_accessor :non_saved_variable
end
这是具有数据库表,让我们在这个表中,我们存储的比赛,姓名和年龄说。
现在我们需要一个控制器,创建/编辑/更新/删除动物
class AnimalController < ActionController::Base
def new
# this creates a new animal with blank values
@animal = Animal.new
end
end
现在你需要进入你的routes.rb,创造动物
resources :animal
这个路线将为动物的每个动作创建所有(平静)路线。
现在你需要有你的模板来呈现形式
的form_for是Rails帮手,创建表单,与@animal(这是一个新的动物)相关联。你传递| f |成块,所以用F你可以访问形式
=form_for @animal do |f|
那么你可以去为每个字段需要调用另一个轨道帮手 您还可以访问attr_accessors。
=f.text_field :race
=f.text_field :name
=f.text_field :age
=f.text_field :non_saved_variable
由你得到的东西
不fortget f.submit
因为你的表单需要一个提交按钮
,如果你现在点击此按钮,表格将被张贴到钢轨的创建方法。所以你需要把它带入你的控制器
def create
# create a new animal with the values sended by the form
@animal = Animal.new params[:animal]
# here you can access the attr_accessor
@animal.do_something if @animal.non_saved_variable == "1337"
if @animal.save
# your animal was saved. you can now redirect or do whatever you want
else
#couldnt be saved, maybe validations have been wrong
#render the same form again
render action: :new
end
end
我希望你能第一次了解rails?!
这是一个非常非常糟糕的做法,绝不应该在rails中完成!请告诉我们为什么你需要这个,我们找到更好的解决方案! –
btw:form_for对象以“f”作为对象的标识符打开一个块。对象是模型的对象,而不是控制器 –
嗯,我想在控制器中有一种临时变量来完成一些可以从窗体接收数据的东西,而且我不擅长导轨所以我不能想出另一种方法,这就是为什么我想出了这个。 – lmatejic