[英]How do I hook up a submit button with my rails database and save it?
我正在尝试将这行代码(它是一个提交按钮)连接到我的 rails 应用程序中的数据库。 我想在给它 post 方法后它会保存。
我试过给它(@message)的参数试图具体
这是按钮的行:
<%= link_to 'Submit', messages_path(@message), method: :post, class: 'btn-submit' %>
这是 controller:
def create
Message.create(message_params)
redirect_to root_path
end
该页面当前只是重新加载而不保存数据。
如果您附上您的Message
model 代码和routes.rb
文件,这将非常有帮助。 但无论如何......我会尽力解释。
通常开发者使用 forms 提交数据。 要创建Message
object,您需要从视图中传递一些数据。 更多关于 forms的信息。 您的视图需要如下所示:
<%= form_for @message do |f| %>
<%= f.text_field :text, class: 'form-control' %> // you need to change it t be a field of your Message model
<%= f.submit "Submit", class: 'btn-submit' %> // this is your submit button
<% end %>
在您的 controller 添加条件以检查是否创建了消息。 更多信息
def create
if Message.create(message_params)
redirect_to root_path # redirect to root path if message created
else
render :new # render action :new in case of errors.
end
end
确保您传递通过Message
model验证所需的所有数据(如果有)。
我希望这会有所帮助。
你也应该检查url表格也在你的rails控制台中发布
您可以通过在终端中运行来检查可用的路径
rake routes | grep message
这应该返回所有包含消息的路由。 确保它找到正确的并匹配!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.