Params를 반환하는 Rails 메서드가 있습니다.
def customer_params
params.require(:treatment_booking).require(:customer)
end
:phone
제자리 에서 공백을 제거 하고 전체 해시를 반환하고 싶습니다 . 그렇게 할 수 있습니다.
params.require(:treatment_booking).require(:customer).merge(:phone => params[:treatment_booking][:customer][:phone].gsub(/\s+/, ""))
..하지만 이미 메서드를 호출 한 해시에 대한 전체 경로를 참조해야하기 때문에 다소 우아하지 않다고 생각합니다. 더 좋은 방법이 있습니까?
답은 Ruby와 Rails가 될 수 있습니다.
일반적으로 내가하는 일은 예약 컨트롤러에서 고객을 업데이트하는 것입니다. 고객은 지속될 수 있지만 비밀번호가 없어서 데이터를 변경할 수 없습니다. 추가 만하면됩니다.
컨트롤러의 내용은 다음과 같습니다.
def create
customer = Customer.find_or_create_by(email: customer_params[:email])
if not customer.persisted?
customer.phone = customer_params[:phone] if not customer_params[:phone].empty?
customer.name = customer_params[:name] if not customer_params[:name].empty?
save_customer(customer)
elsif (customer.phone != customer_params[:phone] || customer.name.downcase != customer_params[:name].downcase)
customer.phone = customer_params[:phone] if customer.phone.empty?
customer.name = customer_params[:name] if customer.name.empty?
save_customer(customer)
redirect_to :back, notice: "This email address has been used before, you can register it or use the same Name and Phone"
return
else
set_session_customer(customer.id)
end
< .. .. >
end
매개 변수를 삭제하는 것은 컨트롤러의 책임이 아니라고 생각합니다. 그러나 속성이 유효한지 확인하는 것은 모델의 책임입니다.
모델 속성을 삭제하려면 Customer
다음과 같이 모델에 사용자 지정 setter를 추가합니다 .
# in app/models/customer.rb
def phone=(phone)
write_attribute(:phone, phone.gsub(/\s+/, ''))
end
그리고 customer_params
컨트롤러를 변경하지 마십시오 .
귀하의 의견을 해결하려면 : 컨트롤러에서 많은 일이 진행되고 있습니다. 그리고 IMO 컨트롤러는 이해하고 리팩토링하기가 어렵습니다. 특히 변경된 속성에 대해 얼마나 엄격한 방법 save_customer
과 set_session_customer
작업을 수행 해야하는지 모르기 때문 입니다.
업데이트 코드를 Customer
모델 로 옮기는 것이 합리적이라고 생각합니다 . 따라서 테스트하기가 더 쉽습니다. 그리고 Rails의 Dirty Attributes를 사용했습니다 .
# in the controller
def create
existing_customer = Customer.find_by(present_customer_params.fetch(:email))
if existing_customer
if existing_customer.contact_detail_update(present_customer_params)
save_customer(existing_customer)
redirect_to(
:back, notice: 'This email address has been used before, you can register it or use the same Name and Phone'
) and return
else
set_session_customer(existing_customer.id)
end
else
new_customer = Customer.create(present_customer_params)
save_customer(new_customer)
end
# ...
end
private
def present_customer_params
# excludes blank values from the customer_params
customer_params.select { |_, v| v.present? }
end
# in the `Contact` model
def contact_detail_update(attrs = {})
contact_attributes = [:phone, :name]
# update the customers attributes and let existing customer setters to their job
attributes = attrs.slice(*contact_attributes)
# check case-insensitively if there were any non-trivial changes
changes.slice(*contact_attributes).values.any? do |change|
change.first.casecmp(change.last) != 0
end
end
이것이 귀하의 의견에 대한 답변인지 확실하지 않지만 아이디어가 향후 리팩토링에 도움이 될 것입니다 ...
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다