zkidd
zkidd

Reputation: 513

After adding a resource (object?) to rails app, how do I get the controller to save it?

I just added this to my _form.html.erb file

<div class="field">
    <%= f.label :street %><br />
    <%= f.text_field :street, autofocus: true, class: "form-control" %>
</div>

and in my show.html.erb file to take the street input I added this

<div class="panel-body">
      <%= @property.description %>
      <%= @property.street %>
 </div>

but the street is not saving. I think I need to change my properties_controller.rb file, but I'm not sure how.

Here is that file:

class PropertiesController < ApplicationController
  before_action :set_property, only: [:show, :edit, :update, :destroy]
  before_action :correct_user, only: [:update, :edit, :destroy]
  before_action :authenticate_user!, except: [:index, :show]


  def index
    @properties = Property.all.order("created_at DESC").paginate(:page => params[:page], :per_page => 3)

  end

  def show
  end

  def new
    @property = current_user.property.build
  end

  def edit
  end

  def create
    @property = current_user.property.build(property_params)

      if @property.save
        redirect_to @property, notice: 'Property was successfully created.'
      else
        render :new
      end
    end


  def update
     if @property.update(property_params)
        redirect_to @property, notice: 'Property was successfully updated.'
     else
        render :edit
    end
  end

  def destroy
    @property.destroy
    respond_to do |format|
      format.html { redirect_to properties_url, notice: 'Property was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    def set_property
      @property = Property.find(params[:id])
    end

    def correct_user
        @property = current_user.property.find_by(id: params[:id])
        redirect_to property_path, notice: "Not authorized to edit this property" if @property.nil?
    end

    def property_params
      params.require(:property).permit(:description, :image)
    end
end

On another related note, what is the proper way to do an address form in rails? Should I eventually have something like,

<div class="field">
    <%= f.label :street %><br />
    <%= f.text_field :street, autofocus: true, class: "form-control" %>
    <%= f.integer_field :zip, autofocus: true, class: "form-control" %>
    <%= f.text_field :city, autofocus: true, class: "form-control" %>
    <%= f.text_field :state, autofocus: true, class: "form-control" %>
</div>

Thanks for the help :)

Upvotes: 0

Views: 36

Answers (1)

Gaurav Gupta
Gaurav Gupta

Reputation: 475

You need to permit 'street'

def property_params
  params.require(:property).permit(:description, :image, :street)
end

Upvotes: 2

Related Questions