在索引页面中,我只是通过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
其中projects_lkps_id has_many stock
现在我的疑问是,当我创建新股票时如何将这个ID形成?
现在我在控制器中的创建方法是
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是
params.require(:stocks).permit(:item,:unit,:projects_lkp_id)
答案 0 :(得分:1)
如果您有嵌套路线,例如
resources :projects do
resources :stocks
end
生成的路线就像 -
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
然后你必须在路线中拥有project_id
,你将能够在控制器中拥有project_id
,而不必拥有形式。控制器代码如下所示
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
和stock_params
将是 -
params.require(:stocks).permit(:item,:unit)