0

Can someone help me make a form? I keep getting ActionView::Template::Error (undefined method `title' for #):

UrlsController

'''

class UrlsController < ApplicationController
  def url_params
    params.require(:url).permit(:title, :link)
  end

  def create
    @url = Url.create!(url_params)
    flash[:notice] = "#{@url.title} was successfully created."
    @url.save
  end

  def new
    @url = Url.new
  end

  def edit
    @url = Url.find(params[:id])
  end

  def update 
    @url = Url.find params[:id]
    @url.update_attributes!(url_params)
    flash[:notice] = "#{@url.title} was successfully updated."
  end
end

'''

new.html.erb

'''

  <h2>Add A URL Reference</h2>
  <%= form_for Url.new do |f| %>
      <%= f.label :title %><br />
      <%= f.text_field  :title %>
      <%= f.label :link %><br />
      <%= f.text_field  :link %>
      <%= f.button :submit %>
  <% end %>

'''

2 Answers2

0

I would suggest you refactor your code like this..

You can take note of the set_url in the private to prevent repetition of codes

class UrlsController < ApplicationController
  before_action :set_url, only: [:show, :edit, :update, :destroy]

  def new
    @url = Url.new
  end

  def edit
  end

  def create
    @url = Url.new(url_params)

    if @url.save
      flash[:success] = Your url was successfully published!]
      redirect_to @url
    else
      render :new
    end
  end

  def update
    if @url.update(url_params)
      flash[:success] = Your url was successfully updated!]
      redirect_to @url
    else
      render :edit 
    end
  end

  private
    def set_url
      @url = Url.find(params[:id])
    end

    def url_params
      params.require(:url).permit(:title, :link)
    end
end

new.html.erb

<h1>New Form</h1>
<%= render 'form', url: @url%>

_form.html.erb

<%= form_for @url do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title %>

  <%= f.label :link %>
  <%= f.text_field :link%>

  <%= f.submit %>
<% end %>

routes.rb

resources :urls

You will want to check devise documentation if you'll be using devise for authentication.

0

You used create with a bang(!) in @url = Url.create!(url_params). It raises an exception when the record is not created. Hence if @url is not created it will throw an error and when you call title on the instance. As @Tolase Adegbite suggested. Remove the code with bang. Initialise the object then call a save without bang operator. If you wish to use bang use a begin and rescue block.