Search code examples
ruby-on-railsrubysqliteassociationslinkage

Rails and SQLITE: Images are not being displayed


I am very new to Rails and Web-programming and hope you can help me out with my very first project. I am developing a website for a Real Estate Agency.

I have 3 tables in my database (Homes: Home_ID, Home_Name, Admin_ID; Admins: Admin_ID, Admin_Name, Admin_Email; Images: Image_ID, Image_Path, Image_Name, Home_ID, Admin_ID).

All 3 tables have been created using scaffold. The image information (name, path, image_id, home_id etc) have been entered in SQLite. I get all text information of the different houses displayed correctly on the website except the pictures.

My attempt to link it in the view/home/index.html.erb created the following error:

undefined method `image_path' for #<Home:0xb63d85e0>

I used below code:

<% @homes.each do |home| %>
  <tr>
    <td><%= home.name %></td>
    <td><%= home.details %></td>
    <td><%= home.region %></td>
    <td><%= home.address %></td>
    <td><%= home.price %></td>
    <td><%= home.admin_id %></td>
    <td><%= home.image_path %></td>
  </tr>
<% end %>
</table>

It looks like that the data entered in SQLite do not sync with rails. Do you have any idea what I have done wrong and how I can fix it?

Thank you.


Solution

  • I'm not positive what the relationship would be between your images and home models would be so correct me if I'm wrong, but I'm guessing that homes will have many images. Each image would belong to one home. Is this correct? If so, you will need to declare that in your models like so:

    models/home.rb

    has_many :images
    

    models/image.rb

    belongs_to :home
    

    You will then need to add this to the image database:

    t.integer  "home_id"
    

    You can add it by going to the command line and typing:

    rails g migration AddHomeToImages home_id:integer
    

    You should look in db/migrate/ and then the most recent migration file and make sure it looks like this:

    add_column :images, :home_id, :integer
    

    Then run:

    rake db:migrate

    At this point you'll only need to update your controller and views to show this association. Let me know if this helps and if so I'll help you with your controller and views.