1

I have two models set up: Photo and Search. Each photo has one associated search, and I want to try and display this associated search in the photo view. Here are my models:

class Photo < ActiveRecord::Base

  has_one :search

end

# Data: name:string, photo_url:string, search_id:integer

Brief aside: I’m unsure whether I need to have the has_many association here or not.

class Search < ActiveRecord::Base

  validates :search_term, :presence => true
  has_many :photos

end

# Data: search_term:string

Here is the controller action:

def index
  @photos = Photo.all
end

And finally, the view templates:

<!-- index.html.erb -->

<section class="photos">
  <%= render @photos %>
</section>

<!-- _photo.html.erb -->

<div class="photo__item">
  <h1><%= photo.id %>: <%= photo.name %></h1>
  <h3>Search_term: <%= photo.search_id.search_term %></h3>
  <%= image_tag(photo.photo_url) %>
</div>

The error I’m getting is:

undefined method `search_term' for 2:Fixnum

I’m not even entirely sure my set up for this is correct, so any help would be greatly appreciated.

2 Answers 2

1

you put the search_id in the photos table, so i think you should make the photo class definition like this

class Photo < ActiveRecord::Base
  belongs_to :search
end

and in the view you you should get the photo's search instance like this

<h3>Search_term: <%= photo.search.search_term %></h3>
Sign up to request clarification or add additional context in comments.

Comments

1

You need to set the correct association. Try changing has_one :search to belongs_to :search.

The belongs_to association is always used in the model that has the foreign key.

See: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

2 Comments

Ah, I’m with you. Which parts should I change in the controller and views?
Try photo.search.search_term`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.