1
votes

New to rails.This problem is most likely due to my misconception of how routing works but unsure. My little program is identical to the Articles blog example on the Ruby on Rails online beginners guide tutorial.

All I want to do is have a button/link in the show.html.erb file that would redirect me to another url, but I need to access the articles ID to access the url, in order to get the title from that article object.

in articles_controller.rb I have:

def join
  @article = Article.find(params[:id]) --->getting error, cant find Article without ID
  redirect_to(**irrelevant code**))
end

in show.html.erb I have:

<%= link_to "Click here", {method: 'get', :controller => "articles", :action => "join"}

in routes.db i have:

get '/articles/join', to: 'articles#join'

I am getting the error ActiveRecord::RecordNotFound in ArticlesController#join Couldn't find Article without an ID

Why doesn't this work for my join method? why is id from params[:id] only extractable in the other CRUD operations?

thanks

4
You seem to not sending the param id from your html. How your join method could know what article you want to get ? So your params[:id] is null. Try to print it and you will see. - sonic
you're right, thanks!! - eTonis
You could also change your route to get '/articles/:id/join', to: 'articles#join' which makes sure an id is required in the path itself. - 3limin4t0r

4 Answers

1
votes

Because your join method require an article id. You need to pass an article in link_to

0
votes

You might be better off using resources syntax in your routes when adding a new action to your controller:

try:

resources :articles do
  member do
    get 'join'
  end
end

which will give you the extra route:

join_article  GET  /articles/:id/join(.format)

so you can then use:

<%= link_to 'Click Here', join_article(@article) %>

in your views.

0
votes

In your example you need to pass :id of the article in the link which is sending your request to action join - currently missing parameter.

<%= link_to "Click here", {method: 'get', :controller => "articles", :action => "join", :id => @article.id } %>

That should set :id and make it accessible in the articles#join action.

0
votes
<%= link_to "Click here", {method: 'get', :controller => "articles", :action => "join", id => @article.id} -%>

get '/articles/join/:id', to: 'articles#join'