hi,
how do i access the has_one relationship in a view?
i have the following
model car has_one picture
picture belongs_to car
picture table contains the car_id in the table as well.
in my view id like to access it like
if @myobj.has_picture?
do stuff.
end…
or id like simply print out
@myobj.picture.filename
i tried this with the has_many relationship and it works.
hi, from doing more research it seems that i may not be collecting the
picture correctly in my controller. i found this exampe in this forum
where the user was having similiar problem.
class Employee < ActiveRecord::Base #employee.rb
has_one :bio
end
class Bio < ActiveRecord::Base #bio.rb
belongs_to :employee
end
@bios = @employees.collect { |employee| employee.bio }.compact
<% @bios.each do |bio|
<%= bio.name %>
%>
#############################
but how can i do this in a view like has_many does?
@obj = Employee.find(:all)
for employees in @obj
print out emplyee stuff
if employee.has_category
print out bio stuff
end
end
do i need a join?
i see i just need to add the include in my find sql query,
@account = Account.find( session[:account_id], :include => {:patients =>
:patient_details } )
but do this with a has_one
hi jason,
the error is undefined field for trying to access car.picture.filename
in my view.
when doing a find in my car table
@carobj = Car.find(:all, :condition=> 'id == ?", idpassed)
does this also get the picture in my picture table since picture belongs
to car table and car model has one picture?
or must i include picture table in my find statement like?
@carobj =
Car.find(:all, (:condition=> 'id == ?", idpassed), :include => :picture)
So, what is the problem you’re having with has_one? The relationships
you’ve
described are correct, so you can do car.picture.filename (assuming
Picture
has a filename field). You’ll have to post your error messages if we are
to
help you.
Jason
Why don’t you go ahead and post the code for the two models and the
controller? Something is messed up in the relationship setup.
For the record, you only need to do:
@carobj = Car.find(idpassed)
which should give you
@carobj.picture
automagically
Jason
the error is undefined picture.
nevermind figured out my problem!
ok, here is my code, i am also quite new to ruby rails/
view…
<% if @viewobj != nil %>
<% for auto in @viewobj %>
<%= auto.date %> - “<%= auto.title %>” etc…
<%= auto.autopicture.filename %> <-----bad! not working
<% end %>
<% end %>
controller…
@pages, @viewobj = paginate_collection Auto.get_all_autos, :page =>
@params[:page]
model auto…
class Auto < ActiveRecord::Base
has_one :autopicture
def self.get_all_autos
Auto.find(:all, :order => “created_at DESC”)
end
end
model autopicture…
acts_as_attachment :storage => :file_system, :max_size => 300.kilobytes,
:content_type => :image
validates_as_attachment
belongs_to :auto
end
thanks for the help!