Reputation: 39
i have some problems with my app, i have posts, posts has_many responces when i create new responce to the post, not added in the db 'responce' post_id my routes.rb
resources :categories do
resources :posts
end
resources :posts do
resources :responces
end
controller
class ResponcesController < ApplicationController
def new
@post = Post.find(params[:post_id])
@responce = @post.responces.new(post_id:params[:post_id])
end
def create
@responce = current_user.responces.build(responce_params)
@post = Post.find(params[:post_id])
if @responce.save
flash[:success] = "Вы откликнулись на задание"
redirect_to post_path @post
else
render 'new'
end
end
def show
end
private
def responce_params
params.require(:responce).permit(:price, :comment, :post_id)
end
end
view
<%= form_for([@post, @responce]) do |f| %>
<%= f.text_area :price %>
<%= f.submit "GO", class: "btn btn-large btn-primary" %>
<% end %>
but if add to the view this
<%= f.collection_select :post_id, Post.all, :id, :name %>
rails create post_id to the db
help
Upvotes: 0
Views: 126
Reputation: 4147
You are doing several things the wrong way.
First: I don't think you need two separate resources for the same model. I'd recomend nesting all three resources upon each other like this.
resource :categories do
resource :posts do
resource :responces
end
end
This way you'll be able to find the needed category_id and post_id in the params hash.
I'd also recomend adding :shalow => true
to the :categories
resource to make your routes a bit prettier.
Second: you need to assign the params[:post_id]
in your create action, like this.
@responce = current_user.responces.build(responce_params)
@responce.post_id = params[:post_id]
@post = @responce.post
Alternatevely you can just add a hidden field to your form like I show below, but it I don't like that approach, 'cause it can lead to security risks.
<%= form_for([@post, @responce]) do |f| %>
<%= f.text_area :price %>
<%= f.hidden_field :post_id, :value => @post.id %>
<%= f.submit "GO", class: "btn btn-large btn-primary" %>
<% end %>
Upvotes: 1
Reputation: 4959
In your form you aren't passing in the post_id. You probably want something like this:
<%= form_for([@post, @responce]) do |f| %>
<%= f.text_area :price %>
<%= f.hidden_field :post_id, :value => @post.id %>
<%= f.submit "GO", class: "btn btn-large btn-primary" %>
<% end %>
The hidden field will pass the id of the current post into your form as the post_id parameter.
Upvotes: 0