Billy Logan
Billy Logan

Reputation: 2520

Error when accessing a resource: "param is missing or the value is empty: article"

I want to pass in the whole object to my show action in order to update its viewed field, but for some reason I keep getting this error.

enter image description here

Why is that?

index.html.erb

<td><%= link_to 'Show', article_path(article) %></td>

controller

  def show
    @article = Article.find(params[:id])
    @article.viewed += 1
    @article.update(article_params)
  end

  private
    def article_params
      params.require(:article).permit!
    end

Upvotes: 0

Views: 50

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176552

In the code you have the following line

params.require(:article).permit!

The require method invocation will raise the error you are experiencing if the params hash doesn't contain an article hash.

As you can see from the error page, your current parameters are

{"id"=>"1"}

There is no article hash. That's the issue.

Checking your code even further, the following line doesn't make sense at all

@article.update(article_params)

You pretend to update the @article from some parameters in the show action. However, you have at least two issues here:

  1. The parameters are not passed in any way
  2. That's a show action and it is not supposed to update a resource

It's likely to me you just want to increment the counter. If that's the case, your action should be

def show
  @article = Article.find(params[:id])
  @article.viewed += 1
  @article.save!
end

or even better you can use increment!

def show
  @article = Article.find(params[:id])
  @article.increment! :viewed
end

Upvotes: 3

Related Questions