2015-11-09 32 views
1

我在回報率以下幾種觀點:帕拉姆從形式不保存

<%= 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保存爲空。奇怪的是,html生成正常:

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

爲什麼?

回答

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

+0

'redirect_to的@ POST'還需要一個'show'行動。 –

+1

是的,但不想混淆OP。如果需要,我將添加「show」的動作和視圖 –