저는이 문제에 대한 많은 자습서를 읽었지만 아무 것도 작동하지 않는 것으로 보입니다. 한 사용자가 물건을 판매 할 부스를 하나 만들도록하려고합니다. 여기 새 모델을 사용자 ID와 연결
class CreateBooths < ActiveRecord::Migration
def change
create_table :booths do |t|
t.string :name
t.references :user, index: true
t.timestamps null: false
end
add_index :booths, [:user_id]
end
end
는 부스 컨트롤러 :
이 내 DB 마이그레이션입니다
class BoothsController < ApplicationController
before_action :logged_in_user
def new
@booth = Booth.new
end
def create
@booth = current_user.booths.build(booth_params)
if @booth.save
flash[:success] = "Congrats on opening your booth!"
redirect_to root_url
else
render 'new'
end
end
private
def booth_params
params.require(:booth).permit(:name)
end
end
그리고 이것은 부스 모델 :
class Booth < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
end
나는 또한이 추가 사용자 모델 :
has_one :booth, dependent: :destroy
validates :user_id, presence: true
을 포함하면 데이터베이스에 저장되지 않습니다. 제외 할 때 데이터베이스에 사용자 ID를 저장하지만 포함시키지 않습니다. 당신이 아직도 고마워하고 있다면, 당신이 도울 수 있기를 바랍니다! 당신이 사용자와 부스 사이의 one-to-one 연관을 가지고
def create
@booth = current_user.build_booth(booth_params)
if @booth.save
flash[:success] = "Congrats on opening your booth!"
redirect_to root_url
else
render 'new'
end
end
을 여기에, 당신은 current_user
이 build_<singular_association_name>
을 사용하는 booth
를 인스턴스화해야 할 이유입니다 :
'current_user'에'id'가 있습니까? – ptd
@ptd :'current_user'를 사용할 수 없다면 OP는 다음과 같이 질문했을 것입니다 : 왜 nil 클래스를위한'booths' 메소드가 정의되지 않았습니까? :) – Surya
@ptd 예, 현재 사용자 ID가 있습니다. 아래의 해답은 잘 작동했습니다. 감사. – Kelly