简体   繁体   中英

Ruby on Rails - Pass ID from another controller

I have two models. First is Taxirecord and second is Carpark. Each Taxirecord may have its own Carpark. I have a problem with passing taxirecord_id to Carpark record. I have route

car_new GET    /taxidetail/:taxirecord_id/carpark/new(.:format) carparks#new

And i want to pass :taxirecord_id, which is id of taxirecord that im editing, to my create controller. My carpark model:

class Carpark < ActiveRecord::Base
    belongs_to :taxirecord
end

In controller im finding taxirecord_id by find function based on param :taxirecord_id, but id is nil when create is called. Can you please help me to find out what Im doing wrong and how Can I solve this problem? Thanks for any help!

My carpark controller

class CarparksController < ApplicationController
    def new
            @car = Carpark.new
    end
    def create
            @car = Carpark.new(carpark_params, taxirecord_id: Taxirecord.find(params[:taxirecord_id]))
            if @car.save
                    flash[:notice] = "Zaznam byl ulozen"
                    redirect_to root_path
            else
                    flash[:notice] = "Zaznam nebyl ulozen"
                    render 'new'
            end

    end
private def carpark_params
                params.require(:carpark).permit(:car_brand, :car_type, :driver_name, :driver_tel)
        end

end

I'd lean towards using something like:

before_action :assign_taxirecord   

...

private

def assign_taxirecord
  @taxirecord = TaxiRecord.find(params[:taxirecord_id])
end

And then in the create action:

def create
  @car = @taxirecord.build_carpark(carpark_params)
  ...
end 

Obviously there's a little tailoring needed to your requirements (ie for what actions the before_action is called), but I hope that helps!

No need to send taxirecord id.

class Carpark < ApplicationRecord
  belongs_to :taxirecord
end


class Taxirecord < ApplicationRecord
  has_one :carpark
end

Rails.application.routes.draw do
  resources :taxirecords do 
    resources :carparks
  end
end


for new taxirecord
 t = Taxirecord.new(:registration => "efgh", :description =>"test")

for new carpark
 t.create_carpark(:description=>"abcd")


#=> #<Carpark id: 2, taxirecord_id: 2, description: "abcd", created_at: "2017-10-12 10:55:38", updated_at: "2017-10-12 10:55:38">

我终于开始工作了<%=link_to 'New Carpark', {:controller => "carparks", :action => "new", :taxirecord_id => @taxi_record.id }%>在我的出租车记录表格中添加了<%=link_to 'New Carpark', {:controller => "carparks", :action => "new", :taxirecord_id => @taxi_record.id }%>停车场表格<%= hidden_field_tag :taxirecord_id, params[:taxirecord_id] %>到我的停车场控制器: @carpark.taxirecord_id = params[:taxirecord_id]感谢大家的大力支持和帮助!

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