表格中的参数未保存

时间:2015-11-09 09:36:33

标签: ruby-on-rails

我在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>

为什么?

2 个答案:

答案 0 :(得分:3)

将您的创建操作修复为:

<?php
echo "
<form method='post'>
<button name='first'>First step</button>
</form>
</div>
";

if (isset($_POST['first']) or isset($_POST['postform']))
{
myFunction();
}

?>

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

答案 1 :(得分:3)

你应该坚持惯例:

#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