domi91c
domi91c

Reputation: 2053

Rails 4: Accessing model through another

I'm having trouble accessing the Picture model setup like:

Request has_one Gallery has_many Pictures

From the show view of the Request model, I need to access its Gallery's Pictures, and it's giving me the error undefined method 'pictures' for nil:NilClass.

Models:

class Request < ActiveRecord::Base
  belongs_to :user
  has_one :gallery
  has_many :pictures, through: :gallery
end

class Gallery < ActiveRecord::Base
  has_many :pictures, :dependent => :destroy
  belongs_to :request
end

class Picture < ActiveRecord::Base
  belongs_to :gallery
  has_attached_file :image,
    :path => ":rails_root/public/images/:id/:filename",
    :url  => "/images/:id/:filename"

  do_not_validate_attachment_file_type :image
end

Requests Controller:

class RequestsController < ApplicationController
  before_action :set_request, only: [:show, :edit, :update, :destroy]

  def show
    @request  = Request.find(params[:id])
    @gallery = @request.gallery
    @pictures = @gallery.pictures
  end

  def new
    @request = Request.new
    @gallery = Gallery.new(params[:request_id])
    @gallery = @request.gallery
    @pictures = @gallery.pictures
  end

  def create
    @request = Request.new(request_params)

    respond_to do |format|
      if @request.save
        format.html { redirect_to @request, notice: 'Request was successfully created.' }
        format.json { render :show, status: :created, location: @request }
      else
        format.html { render :new }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end


  private
    # Use callbacks to share common setup or constraints between actions.
    def set_request
      @request = Request.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def request_params
        params.require(:request).permit(:title, :description, :username, gallery_attributes: [:id, :name, :description]).merge(user_id: current_user.id)
    end
end

Galleries Controller:

class GalleriesController < ApplicationController

  def show
    @gallery  = Gallery.find(params[:id])
    @pictures = @gallery.pictures

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @gallery }
    end
  end

  def new
    @gallery = Gallery.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @gallery }
    end
  end

  def create
    @gallery = Gallery.new(gallery_params)

    respond_to do |format|
      if @gallery.save

        if params[:images]
          params[:images].each { |image|
            @gallery.pictures.create(image: image)
          }
        end

        format.html { redirect_to @gallery, notice: 'Gallery was successfully created.' }
        format.json { render json: @gallery, status: :created, location: @gallery }
      else
        format.html { render action: "new" }
        format.json { render json: @gallery.errors, status: :unprocessable_entity }
      end
    end
  end

  def gallery_params
      params.require(:gallery).permit(:name, :description, :cover, :token)
  end
end

Pictures Controller:

class PicturesController < ApplicationController

  def show
    @picture = Picture.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @picture }
    end
  end


  def new
    @gallery = Gallery.find(params[:gallery_id])
    @picture = @gallery.pictures.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @picture }
    end
  end

  def create
    @picture = Picture.new(params[:picture])

    if @picture.save
      respond_to do |format|
        format.html {
          render :json => [@picture.to_jq_upload].to_json,
          :content_type => 'text/html',
          :layout => false
        }
        format.json {
          render :json => [@picture.to_jq_upload].to_json
        }
      end
    else
      render :json => [{:error => "custom_failure"}], :status => 304
    end
  end

Request show view: (shortened)

<%- model_class = Request -%>
    <% unless @pictures.empty? %>
        <% @pictures.each do |pic| %>
            <li class="span3" id="picture_<%= pic.id %>">
              <div class="thumbnail">
                <%= image_tag pic.image.url %>
                <div class="caption">                       
                </div>
              </div>
            </li>
        <% end %>
    <% end %>

In the Request show view, I'm trying to access @pictures, which should give me all the pictures of the request's gallery. I hate posting so much code but am new to this and don't want to leave anything out. Any ideas?

Upvotes: 2

Views: 111

Answers (1)

Alexander Kireyev
Alexander Kireyev

Reputation: 10825

This parts has strong issues:

def show
  @request  = Request.find(params[:id])
  @gallery = @request.gallery
  @pictures = @gallery.pictures
end

def new
  @request = Request.new
  @gallery = Gallery.new(params[:request_id])
  @gallery = @request.gallery
  @pictures = @gallery.pictures
end

In show you need to check if request has gallery or not (if you don't add validation on the association, you can do it like: validates_presence_of :gallery in Request model). Another way is add nil check:

 def show
  @request  = Request.find(params[:id])
  unless @request.gallery.nil?
    @gallery = @request.gallery
    @pictures = @gallery.pictures
  end
end

But if you expect this models, add association:

class Request < ActiveRecord::Base
  belongs_to :user
  has_one :gallery
  validates_presence_of :gallery
  has_many :pictures, through: :gallery
end

Also in new action just have just create @request there is no gallery associated with it. Also you define @gallery 2 times, i don't know the reason. You could build it:

def new
  @request = Request.new
  @gallery = @request.build_gallery
  @pictures = @gallery.pictures
end

I can't also understand what is params[:request_id]. If it's new for request what id you have already?

Updated

As i can see now you need just change new action.

def new
  @request = Request.new
end

Upvotes: 1

Related Questions