ruby-on-rails - 如何使用 button_to 提交表单?

标签 ruby-on-rails ruby

我需要提交并保存一些数据。我需要表单中的一些帖子 ID:

def message_post_collection_params
    params.require(:message_post).permit(
      { post_ids: [] }
    )
end

如何通过 button_to 获取 ID?我的代码:

button_to('Submit', approve_collection_message_posts_path, params: { message_post: { post_ids: ['1', '2'] } }, data: { config: 'Are you sure?', remote: true })

但是报错:

undefined method `permit' for #<String:0x007ffbdf9f1540>

在线 params.require(:message_post).permit(.

我该如何解决?

最佳答案

我对 Mike K 的回答投反对票的原因是参数声明似乎不是问题所在:

enter image description here

我认为问题在于您如何分配 paramsbutton_to :

button_to 'Submit', approve_collection_message_posts_path, params: { message_post: { post_ids: ['1', '2'] } }, data: { config: 'Are you sure?', remote: true }

enter image description here

通知:<input type="hidden" name="message_post" value="post_ids%5B%5D=1&amp;post_ids%5B%5D=2" />

这就是您收到错误的原因(您的数组中没有嵌套)——您的参数字面上看起来像:"message_post" => "post_ids%5B%5D=1&amp;post_ids%5B%5D=2"


修复

有一种便宜的方法可以修复它:

def message_post_collection_params
   params.permit(post_ids:[])
end

= button_to 'Submit',  path_helper, params: { post_ids: ["1","2"] }, data: { config: 'Are you sure?', remote: true }

enter image description here

--

如果你想保留你的嵌套,你可以使用 following comment :

Note that the params option currently don't allow nested hashes. Example: params: {user: {active: false}} is not allowed. You can bypass this using the uglyparams: {:"user[active]" => true}

params: {:"message_post[post_ids]" => ["1","2"]}

enter image description here

关于ruby-on-rails - 如何使用 button_to 提交表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33204073/

相关文章:

ruby - 为什么我们没有一个 group_by!在 ruby​​ 可枚举模块中?

ruby - 在 Ruby 错误中调试 cucumber

ruby - 不确定从 api 返回的是什么 ruby​​ 数据结构

ruby-on-rails - RSpec View 测试找不到基本命名空间中的部分

css - Foundation Icon 字体未正确调整大小

Javascript 计算未在 Rails 嵌套表单内触发

ruby-on-rails - 期望同一个类的多个 Rails Active Job 使用不同的参数入队

javascript - Rails 设计 + omniauth-stripe-connect "Authorization code does not belong to you"

ruby - 测试抽象的 if 条件

ruby - 维护已创建对象集合的最佳方法