On 4 July 2016 at 12:38, Ruth Stephenson <lists@ruby-forum.com> wrote:
> I've been stuck with this for days. I think I should be able to access a
> variable in a controller of one model, that is stored in another model
> easily?
>
> I have four models: User - (1-1) - Profile - (1-M) - Appointment - (1-1)
> - Option.
>
> Options contains pricePerPerson and discount for an appointment.
> Appointments contains, among others, numPeople. I want to access the
> figure in the Options model for the pricePerPerson (and discount, if
> appropriate) and use it in the view show for Appointments. (@ <%=
> appointment.price = Option.pricePerPerson * numPeople %>)
>
> So far I haven't been able to do this and have had to resort to
> hard-coding a price per person. I would rather not hard-code that, if
> possible.
>
> I thought I could do this either of the two ways:
>
> Please can someone tell me how I might go about solving this without
> deleting any tables. I want to keep the database as is if possible.
>
> 1: as there is a belongs_to relationship between options and
> appointments - (Options belongs to appointments)
In that case if you have appointment, say @appointment, and it has an
option that it belongs to then you can say
@appointment.price = @appointment.option.pricePerPerson * numPeople
but you should not do this as that means you are saving (effectively)
the same information in two places in the database, instead define an
access method in appointment.rb that defines the method price() to
return self.option.pricePerPerson*numPeople.
Also, it advise sticking to the rails conventions on naming (so
price_per_person etc). Otherwise you will find that some of the rails
magic may not work.
Further, I suggest again (I believe I have previously suggested that
you do this) that you work right through railstutorial.org, including
the exercises, in order to get an understanding of the basics of
rails.
Colin
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAL%3D0gLvYyzRV8uOKE3DKHA24cDNf%2BK0Sg%2BnUy_tgbhv19feUYg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment