1

I've the following view in 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 %>

And the action of controller:

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

 @post.save!
end

Unfortunately, user_id is saved as null. What is strange, the html is generated properly:

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

Why?

pwas
  • 3,225
  • 18
  • 40

2 Answers2

3

Fix your create action to:

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

  @post.save!
end

I suggest you read Accessing elements of nested hashes in ruby.

Community
  • 1
  • 1
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
3

You should stick to convention:

#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 %>

This will allow you to access url.com/posts/new to create a new post

Richard Peck
  • 76,116
  • 9
  • 93
  • 147