简体   繁体   中英

rails 4 how to pass post_id to the db

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM