【问题标题】:Ruby on rails submit button doesn't call the controllerRuby on rails 提交按钮不调用控制器
【发布时间】:2016-10-11 11:43:15
【问题描述】:

我是 ruby​​ on rails 的新手, 我想制作一个简单的文本字段,您可以在其中更改内容并将其存储在数据库中。但是提交按钮不会调用 Profiles 控制器。 "Foo" 永远不会被提出。

routes.rb:

Rails.application.routes.draw do
   devise_for :users
   get 'welcome/user'
   resources :profiles
end

user.html.erb:

...
<%@profile=Profile.find_by user_id: current_user.id%>
<%= form_for (@profile) do |f| %>
<%= f.text_field :name%>
<%= f.submit%>
<% end %>

profiles_controller.rb:

class ProfilesController < ActionController::Base
  def update
     raise "foo"
  end
end

【问题讨论】:

  • 查看你的服务器,看看调用了什么动作
  • &lt;%@profile=Profile.find_by user_id: current_user.id%&gt; - 那东西肯定属于控制器。
  • 可能,您需要向form_for helper 提供操作。
  • 如果我把它改成这个&lt;%= form_for (@profile) , :url =&gt; url_for(:action =&gt; "update", :controller =&gt; "profiles", :profile_id =&gt; @profile.id) do |f| %&gt; 然后没有路由匹配{:action=&gt;"update", :controller=&gt;"profiles", :profile_id=&gt;3}

标签: ruby-on-rails ruby controller submit call


【解决方案1】:

你真的应该把它分开。

class ProfilesController < ActionController::Base
  def edit
    @profile = Profile.find_by(user_id: current_user.id)
  end

  def update
    raise "Foo"
  end
end

并创建相关的视图文件,edit.html.erb:

<%= form_for (@profile, method: ) do |f| %>
  <%= f.text_field :name %>
  <%= f.submit %>
<% end %>

至于问题本身,我建议您查看日志文件。在您的终端上运行tail -f /path/to/app/log/*,然后尝试提交表单。您在这里看不到任何东西是不寻常的,如果是这种情况,请使用浏览器的开发人员工具检查表单。你应该有类似的东西:

<form id="profile-form" action="/profiles/1" method="post">
...
</form> 

注意action="/profiles/1,其中 1 是配置文件实体的 ID。

【讨论】:

  • 谢谢,“foo”-message 确实被提出了,我希望在浏览器中看到它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 2014-01-13
相关资源
最近更新 更多