Programing

has_many에 레코드를 추가하는 방법 : rails의 연관을 통해

lottogame 2020. 9. 2. 20:21
반응형

has_many에 레코드를 추가하는 방법 : rails의 연관을 통해


class Agents << ActiveRecord::Base
  belongs_to :customer
  belongs_to :house
end

class Customer << ActiveRecord::Base
  has_many :agents
  has_many :houses, through: :agents
end

class House << ActiveRecord::Base
  has_many :agents
  has_many :customers, through: :agents
end

Agents모델에 Customer어떻게 추가 합니까?

이것이 최선의 방법입니까?

Customer.find(1).agents.create(customer_id: 1, house_id: 1)

위의 내용은 콘솔에서 잘 작동하지만 실제 응용 프로그램에서이를 달성하는 방법을 모르겠습니다.

house_id입력으로 도 사용되는 고객을 위해 양식이 채워져 있다고 상상해보십시오 . 그런 다음 컨트롤러에서 다음을 수행합니까?

def create 
  @customer = Customer.new(params[:customer])
  @customer.agents.create(customer_id: @customer.id, house_id: params[:house_id])
  @customer.save
end

전반적으로 has_many :through테이블 에 레코드를 추가하는 방법에 대해 혼란 스럽 습니까?


나는 당신이 간단히 할 수 있다고 생각합니다.

 @cust = Customer.new(params[:customer])
 @cust.houses << House.find(params[:house_id])

또는 고객을 위해 새 집을 만들 때 :

 @cust = Customer.new(params[:customer])
 @cust.houses.create(params[:house])

ID를 통해 추가 할 수도 있습니다.

@cust.house_ids << House.find(params[:house_id])

'가장 좋은 방법'은 귀하의 필요와 가장 편안한 느낌에 따라 다릅니다. ActiveRecord의 newcreate메서드 동작 <<연산자 의 차이로 인해 혼란이 발생 합니다 .

new방법

new연결 레코드를 추가하지 않습니다. 직접 작성 House하고 Agent기록 해야합니다 .

house = @cust.houses.new(params[:house])
house.save
agent = Agent(customer_id: @cust.id, house_id: house.id)
agent.save

참고 그 @cust.houses.newHouse.new당신이 작성해야하기 때문에 효율적으로 동일한 Agent두 경우 모두에서 기록을.

<<운영자

Mischa가 언급했듯이 <<컬렉션 에서 연산자를 사용할 수도 있습니다 . 이렇게하면 Agent모델 만 빌드되며 모델을 빌드해야합니다 House.

house = House.create(params[:house])
@cust.houses << house
agent = @cust.houses.find(house.id)

create방법

createHouseAgent레코드를 모두 빌드 하지만 Agent뷰 또는 API로 반환 하려면 모델 을 찾아야합니다 .

house = @cust.houses.create(params[:house])
agent = @cust.agents.where(house: house.id).first

마지막으로, 생성 할 때 예외가 발생 house하도록하려면 bang 연산자를 대신 사용하십시오 (예 : new!and create!).


Another way to add associations is by using the foreign key columns:

agent = Agent.new(...)
agent.house = House.find(...)
agent.customer = Customer.find(...)
agent.save

Or use the exact column names, passing the ID of the associated record instead of the record.

agent.house_id = house.id
agent.customer_id = customer.id

참고URL : https://stackoverflow.com/questions/7297338/how-to-add-records-to-has-many-through-association-in-rails

반응형