Menporul Poriyalan
Menporul Poriyalan

Reputation: 132

How to bring the belongs_to table id to the form?

In the index page i just filter the results by the projects_lkp_id.

def index
  @filter = params[:projects_lkps_id] || ProjectsLkp.premitted_homes(current_user).first.id
  @stock = Stock.where("projects_lkp_id = ?", @filter)
end

where projects_lkps_id has_many stocks

now my doubt is, when i create new stock how to bring this id to form? .

now my create method in controller is

def create

  @stock = Stock.new(stock_params)

  respond_to do |format|

    if @stock.save
      format.html{ redirect_to stocks_path(id: @stock.id), notice: "Item added to gallery" }
    else
      @stock = Stock.where(item: @stock.item).all
      format.html { render 'index' }
     end
  end
end

stock_params is

 params.require(:stocks).permit(:item,:unit,:projects_lkp_id)

Upvotes: 0

Views: 50

Answers (1)

Vishnu Atrai
Vishnu Atrai

Reputation: 2368

If you have nested routes, like

resources :projects do 
  resources :stocks
end

Generated routes will be like -

project_stocks GET    /projects/:project_id/stocks(.:format)                                                stocks#index
                                           POST   /projects/:project_id/stocks(.:format)                                                stocks#create
new_project_stock GET    /projects/:project_id/stocks/new(.:format)                                            stocks#new
edit_project_stock GET    /projects/:project_id/stocks/:id/edit(.:format)                                       stocks#edit
project_stock GET    /projects/:project_id/stocks/:id(.:format)                                            stocks#show
                                           PATCH  /projects/:project_id/stocks/:id(.:format)                                            stocks#update
                                           PUT    /projects/:project_id/stocks/:id(.:format)                                            stocks#update
                                           DELETE /projects/:project_id/stocks/:id(.:format)                                            stocks#destroy

Then you will have to have project_id in routes and you will be able to have project_id in controller, without having in form. Controller code will be like below

def create
  @project = Project.find(params[:projects_id])
  @stock = @project.stocks.new(stock_params) 
  respond_to do |format|
    if @stock.save
     format.html{ redirect_to projects_stocks_path(@project), notice: "Item added to gallery" }
    else
      @stock = Stock.where(item: @stock.item).all
      format.html { render 'index' }
     end
    end
  end  

and stock_params will be -

params.require(:stocks).permit(:item,:unit)

Upvotes: 1

Related Questions