0

我正在使用最好的 gem,我希望未登录的用户配置文件(不是当前用户)上的字段处于只读模式。ATM 用户可以登录,访问另一个用户页面并更改他们的个人资料选项(它不会保存到数据库中)。应该设置它,以便如果您不是当前用户,那么所有配置文件信息都将是只读的。

显示.html.erb:

<p>Education: <%= best_in_place @user, :education, nil: 'What is your education level?', :type => :select, :collection => [["High school", "High school"], ["Some college", "Some college"], ["Undergraduate", "Undergraduate"], ["Bachelor's", "Bachelor's"], ["Master's", "Master's"], ["PhD", "PhD"], ["Business school", "Business school"], ["Law school", "Law school"], ["Medical school", "Medical school"]] %></p>

用户控制器:

   def update
      @user = if current_user.has_role?(:admin)
            User.find(params[:id])
          else
            current_user
          end
         @user.update_attributes(params[:user])
         respond_with @user
        end

 def edit
      @user = User.find(params[:id])
end
4

1 回答 1

1

我不确定最好的 gem 做了什么,但是对于常规表单,您需要将readonly: true选项添加到视图中的字段中。我假设您的edit视图还为视图提供了@user实例变量。

就像是:

<% if current_user.id == @user.id %>
  <p>Education: <%= best_in_place @user, :education, nil: 'What is your education level?', :type => :select, :collection => [["High school", "High school"], ["Some college", "Some college"], ["Undergraduate", "Undergraduate"], ["Bachelor's", "Bachelor's"], ["Master's", "Master's"], ["PhD", "PhD"], ["Business school", "Business school"], ["Law school", "Law school"], ["Medical school", "Medical school"]] %></p>
<% else %>
  <p>Education: <%= best_in_place @user, :education, nil: 'What is your education level?', :type => :select, :collection => [["High school", "High school"], ["Some college", "Some college"], ["Undergraduate", "Undergraduate"], ["Bachelor's", "Bachelor's"], ["Master's", "Master's"], ["PhD", "PhD"], ["Business school", "Business school"], ["Law school", "Law school"], ["Medical school", "Medical school"]], readonly: true %></p>
<% end %>

希望有帮助。

编辑:

似乎普通的 Rails 辅助选项不可用,所以尝试直接添加 HTML disabled 属性,如下所示:

<% if current_user.id == @user.id %>
  <p>Education: <%= best_in_place @user, :education, nil: 'What is your education level?', :type => :select, :collection => [["High school", "High school"], ["Some college", "Some college"], ["Undergraduate", "Undergraduate"], ["Bachelor's", "Bachelor's"], ["Master's", "Master's"], ["PhD", "PhD"], ["Business school", "Business school"], ["Law school", "Law school"], ["Medical school", "Medical school"]] %></p>
<% else %>
  <p>Education: <%= best_in_place @user, :education, nil: 'What is your education level?', :type => :select, :collection => [["High school", "High school"], ["Some college", "Some college"], ["Undergraduate", "Undergraduate"], ["Bachelor's", "Bachelor's"], ["Master's", "Master's"], ["PhD", "PhD"], ["Business school", "Business school"], ["Law school", "Law school"], ["Medical school", "Medical school"]], :html_attrs => {:disabled => true} %></p>
<% end %>
于 2013-12-02T21:39:13.100 回答