Search code examples
ruby-on-railsblogs

How can i get User name in a table where user_id is used as foreign key


I am using Devise gem for user Authentication. User id is as foreign key in article table How can i get writer name through User_id in a view Show_article.html.erb I can access user_id in show_article.htmlerb

I have tried to make a custom function in article controller but could not get the desired output


Solution

  • your Article model should look like this:

    class Article << ActiveRecord::Base
      belongs_to :user
      #....some more lines
    end
    

    your User model should look like this:

    class User << ActiveRecord::Base
      has_many :articles
      #....some more lines
    end
    

    and your show.html.erb should say:

      #....your rest of code
    <%= @article.try(:user).try(:name) %>
      #....your rest of code
    

    This will skip user name if you article doesn't have any user. It looks like your article doesn't have user_id or you haven't defined your relations correctly.