我对红宝石和铁轨都很陌生。
我已经坚持了好几天。我想我应该能够在一个模型的控制器中访问变量,它很容易存储在另一个模型中?
我有四个模型:User
- (1-1) - Profile
- (1-M) - Appointment
- (1-1) - Option
。
选项包含pricePerPerson
和discount
作为约会。约会包含numPeople
等。
我想访问Option
的{{1}}模型中的数字(如果合适,还有pricePerPerson
),并在discount
的视图展示中使用它。
(@ Appointment
)
到目前为止,我还没有能够做到这一点,不得不求助于每人的硬编码。如果可能的话,我宁愿不硬编码。
到目前为止,系统正在说数据库中没有任何内容(价格为零。我不知道为什么我已经输入了这个数字。它正在跳过"否则& #34;该方法的一部分。(基本上,无论如何,它都会一直返回6)
Appointments.rb型号:
<%= appointment.price = Option.pricePerPerson * numPeople %>
约会控制员:
def calculatePrice
if option.present?
return option.pricePerPerson*numpeople
else
return 6
end
end
选项控制器:
def show
@appointment = Appointment.find(params[:id])
end
def new
@appointment = Appointment.new
@appointment.price
end
def create
@appointment = Appointment.new(appointment_params)
respond_to do |format|
if @appointment.save
format.html { redirect_to @appointment, notice: 'Appointment was
successfully created.' }
format.json { render :show, status: :created, location: @appointment }
else
format.html { render :new }
format.json { render json: @appointment.errors, status:
:unprocessable_entity }
end
end
end
options.rb model:
def new
@option = Option.new
end
def create
@option = Option.new(option_params)
respond_to do |format|
if @option.save
format.html { redirect_to @option, notice: 'Option was successfully
created.' }
format.json { render :show, status: :created, location: @option }
else
format.html { render :new }
format.json { render json: @option.errors, status: :unprocessable_entity
}
end
end
end
数据库架构:
class Option < ActiveRecord::Base
belongs_to :appointment
end
答案 0 :(得分:0)
我同意这些意见。您可能可以简化数据库架构。 但是,如果您想要坚持您的架构并且您希望能够自己调试代码(在简单的情况下),我建议您在Gemfile中安装以下gem。当你的代码出现问题时,它会帮助你理解在哪里,并会显示一个允许你测试一些新代码的控制台。
group :development, :test do
gem 'binding_of_caller'
gem 'better_errors'
gem 'pry-byebug'
end