开发者

how do make edit on viewable to original poster the posts are called 'car' in my app RoR

undefined local variable or method `current_user' for #<ActionView::Base:0x4cdbb48>
Extracted source (around line #7):

4:     <dd开发者_运维知识库>
5:     <%= car.name %><br />
6:     <%= car.description %><br />
7:     <%= link_to('edit', edit_post_path(@car)) if current_user.cars.include?(@car) %>
8:     <%= link_to "Delete", 
9:     :controller => :car, 
10:    :action => :delete,

I am using session[:user_id] = @user.id to track current users login and car.id for the post id, how do I link the two together so that only the original person who posted can view the edit link?? Please help me out


personaly, to solve similar problems I've used the devise gem.

Then I make sure I have an association of some sort between the user and car tables (to use your example) and then put a simple erb check to see if they are matching. If they aren't, use the read only view otherwise allow the editable view. The erb check would look something like this.

<% if current_user.id = car.owner.id %>
  ...show the editable view... 
<% else %>
  ...show the read only view...
<% end %>

If you simply don't want them to see the view if they don't "own" it, you can use a before_filter in your controller to check the user to car relationship and then do the "right thing" based upon your required application requirements. You can forward to an unauthorized action view or simply redirect them to a safe place.

Also, you can simply hide the links or buttons that would lead to the view, but no matter what I'd protect in the controller as well.

I hope this helps a bit...

EDIT: I should say that using the devise gem provides me with total 'user' support out of the box, and then you can relatively easily tailor it to your specific business requirements.


You say that you have the logged in user in @user, so you could simply do this:

<%= link_to('edit', edit_post_path(@car)) if @car.user_id == @user.id %>

I recommend using ActiveRecord's associations - they will come in handy in this and other scenarios.

app/models/user.rb

Class User < ActiveRecord::Base
  has_many :posts
  ...
end

app/models/post.rb

Class Post < ActiveRecord::Base
  belongs_to :user
  ...
end

Then in your view template you could do:

<%= link_to('edit', edit_post_path(@car)) if @user.posts.include?(@car) %>

For clarity, I highly recommend using the model name for variable names whenever possible e.g. @post instead of "@car" for instances of the Post model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜