我有问题:我的表格就是那个
<%=form_for :abbonamentos, url: url_for( :controller => :abbonamentos, :action => :edit) do |f| %>
<div class="field">
<%= f.label :id%><br />
<%= f.text_field :id%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and my controller is that:
def edit
id = params[:abbonamentos][:id]
@b = Abbonamento.find_by_id(id)
@user = current_user
a=Abbonamento.find_by(user_id: @user.id)
if a and @b
a.update_column(:stato_ingresso, (a.stato_ingresso-1))
@stato = a.stato_ingresso
flash[:success] = "Abbonamento used"
redirect_to :scegli_posti
else
flash.now[:error] = "Non ha abbonamento lo deve acquistare."
end
end
我想验证模型Abbonamento中是否存在params id ...当我尝试时我有这样的错误: AbbonamentosController#edit中的NoMethodError 未定义的方法`[]'为nil:NilClass
谢谢
请可能是我无法解释自己。在我想做的研究中,我想用户已经在他的id(user_id)中注册了Abbonamento表。当用户在表abbonamento中注册时,将返回的注册是abbonamento_id,可以是1或2。当他想要使用订阅时,您必须在那里插入代码(abbonamento_id),以便应用程序可以在执行操作之前检查代码是对还是错。如果这是真的,应用程序将采取行动,否则它将成为另一个行动。 实际上我会用rails来实现。谢谢
Started POST "/usa_abbonamento" for 127.0.0.1 at 2014-04-30 14:29:00 +0200
Processing by AbbonamentosController#edit as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8Ydr6NPDkynPQd9zo42vgxNIsNSwz4SPkI0JNzfc4lQ=", "abbonamentos"=>{"id"=>"1"}, "commit"=>"Save Abbonamentos"}
[1m[35mUser Load (0.4ms)[0m SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'c2bc8173fcb2c5cce4b2606962859049830be6aa' LIMIT 1
[1m[36mAbbonamento Load (0.4ms)[0m [1mSELECT "abbonamentos".* FROM "abbonamentos" WHERE "abbonamentos"."user_id" = 1[0m
[1m[35mAbbonamento Load (0.3ms)[0m SELECT "abbonamentos".* FROM "abbonamentos" WHERE "abbonamentos"."id" IS NULL
Rendered abbonamentos/edit.html.erb within layouts/application (3.2ms)
Rendered layouts/_header.html.erb (1.1ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 47ms (Views: 40.2ms | ActiveRecord: 1.2ms)
答案 0 :(得分:0)
将您的控制器代码更改为
def edit
id = params[:abbonamentos][:id]
@b = Abbonamento.where(:id => id)
@user = current_user
a=Abbonamento.where(:user_id => @user.id)
if a.present? and @b.present?
a.update_column(:stato_ingresso, (a.stato_ingresso-1))
@stato = a.stato_ingresso
flash[:success] = "Abbonamento used"
redirect_to :scegli_posti
else
flash.now[:error] = "Non ha abbonamento lo deve acquistare."
end
end
您可以使用present?
或blank?
方法检查行是否存在。