user2514224
user2514224

Reputation: 197

How to hide html areas depending on user in Rails 4?

I have a checkout button on my product page show view which accepts the offer. Each offer belongs_to a user. I don't want the user who created the offer to be able to accept it themselves so if it is the current user on the page I want to hide the button. I can't figure out why this code doesn't work:

<% unless current_user.id == @offer.sender_id %> #sender_id is a foreign key in the offer model that makes each offer belong_to a user.

<div id="accept_offer">
  <%= button_to 'Accept Offer', etc  %>
</div>
    <% end %>

current_user is a devise gem method I believe.

Any help appreciated.

Upvotes: 0

Views: 179

Answers (2)

Billy Chan
Billy Chan

Reputation: 24815

Just saw the error and got the reason.

You tried the page without sign in so unless current_user works, this means you have not signed in. Your original code doesn't considered this case.

Generally you should see an error as current_user is not defined but you may have disabled that.

Two ways to fix:

  1. Change current_user, assign an object in any case

    class ApplicationController
      def current_user
        super || User.new
      end
    end
    
  2. Change the logic

    <% if current_user && current_user != @obj.sender %> 
      # Button code
      # Only signed in user with different id can see it
    

Upvotes: 0

amine
amine

Reputation: 522

your code seems correct, you maybe need to look into your Offer.sender_id attribute in the model to see if it contains the right user id (of the creator of the offer). You could check that by creating a new offer throught your application (in the browser) then, in the console you type:

Offer.last.sender_id

And check if it corresponds to your current_user id

Upvotes: 1

Related Questions