我是 ruby 和 rails 的新手。在我的 Rails 应用程序中,我正在尝试使用 Wicked Wizard gem,需要一些帮助来了解我在代码中遇到的 cattr_accessor
create_table "pets", force: :cascade do |t|
t.string "name"
t.string "colour"
t.string "owner_name"
t.text "identifying_characteristics"
t.text "special_instructions"
t.datetime "created_at"
t.datetime "updated_at"
t.string "email"
t.string "password"
end
模型
class Pet < ActiveRecord::Base
has_many :pet_photos
cattr_accessor :form_steps do
%w(identity characteristics instructions)
end
attr_accessor :form_step
validates :email, presence: true
validates :name, :owner_name, presence: true, if: -> { required_for_step?(:identity) }
validates :identifying_characteristics, :colour, presence: true, if: -> { required_for_step?(:characteristics) }
validates :special_instructions, presence: true, if: -> { required_for_step?(:instructions) }
def required_for_step?(step)
return true if form_step.nil?
return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step)
end
end
和
class Pet::StepsController < ApplicationController
include Wicked::Wizard
steps *Pet.form_steps
def show
@pet = Pet.find(params[:pet_id])
render_wizard
end
def update
@pet = Pet.find(params[:pet_id])
@pet.update(pet_params(step))
if params[:images]
params[:images].each do |image|
@pet.pet_photos.create(image: image)
end
end
render_wizard @pet
end
private
def pet_params(step)
permitted_attributes = case step
when "identity"
[:name, :owner_name]
when "characteristics"
[:colour, :identifying_characteristics]
when "instructions"
[:special_instructions]
end
params.require(:pet).permit(permitted_attributes).merge(form_step: step)
end
end
路线
PetThing::Application.routes.draw do
resources :pets, only: [:new, :create, :index, :destroy] do
resources :steps, only: [:show, :update], controller: 'pet/steps'
end
root to: 'pets#index'
现在我的问题是
1)cattr_accessor
和有什么区别attr_accessor
?
cattr_accessor :form_steps do
%w(identity characteristics instructions)
end
attr_accessor :form_step
2)为什么两个不同的符号( :form_steps
, :form_step
) 分别用作 和 方法的方法cattr_accessor
参数attr_accessor
?
3)为什么将块作为参数传递给cattr_accessor
方法?
非常感谢任何帮助。谢谢