【问题标题】:Param from form not saved表单中的参数未保存
【发布时间】:2015-11-09 17:44:23
【问题描述】:

我在 RoR 中有以下观点:

<%= form_tag(url_for :controller => 'posts', :action => 'create', method: "post") do %>
  <label>Zawartość</label>
  <%= text_area_tag(:content) %>
  <br/>
  <label>Użytkownik</label>
  <%= collection_select(:user, :user_id, User.all, :id, :name ) %>
  <br/>
<% end %>

以及控制器的动作:

def create
 @post = Post.new
 @post.content = params["content"]
 @post.user_id = params["user[user_id]"];

 @post.save!
end

很遗憾,user_id 被保存为 null。奇怪的是,html是正确生成的:

<select name="user[user_id]" ... >...</select>

为什么?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    将您的创建操作修复为:

    def create
      @post = Post.new
      @post.content = params["content"]
      @post.user_id = params["user"]["user_id"];
    
      @post.save!
    end
    

    我建议你阅读Accessing elements of nested hashes in ruby

    【讨论】:

      【解决方案2】:

      你应该遵守约定:

      #config/routes.rb
      resources :posts
      
      #app/controllers/posts_controller.rb
      class PostsController < ApplicationController
         def new
             @post = Post.new
         end
      
         def create
             @post = Post.new post_params
             redirect_to @post if @post.save #-> needs "show" action which I can explain if required
         end
      
         private
      
         def post_params
             params.reqire(:post).permit(:content, :user_id)
         end
      end
      
      #app/views/posts/new.html.erb
      <%= form_for @post do |f| %>
         <%= f.text_area :content %>
         <%= f.collection_select :user_id, User.all, :id, :name %>
         <%= f.submit %>
      <% end %>
      

      这将允许您访问url.com/posts/new 以创建新的post

      【讨论】:

      • 是的,但不想混淆 OP。如果需要,我将为show 添加操作和视图
      猜你喜欢
      • 1970-01-01
      • 2014-04-21
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多