简体   繁体   English

每个都与Ruby on Rails中的if条件一起使用

[英]each do with if condition in Ruby on Rails

I would like to create a list of objects called preference but only include preferences of the current user. 我想创建一个称为preference的对象列表,但只包括当前用户的首选项。 I tried it with the following code: 我用以下代码尝试了它:

<% if logged_in? %>
  <div class="center jumbotron">
    <p id="notice"><%= notice %></p>

    <h1>Präferenzen anzeigen</h1>

    <table>
      <thead>
        <tr>
          <th>Institute</th>
          <th>Preference value</th>
          <th colspan="3"></th>
        </tr>
      </thead>

      <tbody>
        <% @preferences if (user_id  == current_user.id).each do |preference| %>
          <tr>
            <td><%= preference.institute_id %></td>
            <td><%= preference.preference_value %></td>
            <td><%= link_to 'Bearbeiten', edit_preference_path(preference) %></td>
            <td><%= link_to 'Löschen', preference, method: :delete, data: { confirm: 'Are you sure?' } %></td>
          </tr>
        <% end %>
      </tbody>
    </table>

    <br>

    <%= link_to 'Neue Präferenz anlegen', new_preference_path %>
  </div>
<% end %>

Unfortunately I get the error: 不幸的是我得到了错误:

undefined local variable or method `user_id' for #<#:0x007f8ea83ed030> Did you mean? #<#:0x007f8ea83ed030>的未定义局部变量或方法`user_id'是什么意思? user_url user_url

for line 17. 对于第17行

<% @preferences if (user_id  == current_user.id).each do |preference| %>

how can I fix my code? 如何修复我的代码? Is there an easy way or do I need to try it with helpers? 有没有简单的方法,或者我需要与助手一起尝试?

Thanks may times for your help guys! 谢谢您的帮助!

Here is my sessions helper: 这是我的会话助手:

module SessionsHelper

  # Logs in the current user
  def log_in(user)
    session[:user_id] = user.id
  end

  # Remembers a user in a persistent session.
  def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  def current_user?(user)
    user == current_user
  end

  # Returns the user corresponding to the remember token cookie.
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(:remember, cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end

  # Forgets a persistent session.
  def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
  end

  # Logs out the current user.
  def log_out
    forget(current_user)
    session.delete(:user_id)
    @current_user = nil
  end

  # Redirects to stored location (or to the default).
  def redirect_back_or(default)
    redirect_to(session[:forwarding_url] || default)
    session.delete(:forwarding_url)
  end

  # Stores the URL trying to be accessed.
  def store_location
    session[:forwarding_url] = request.original_url if request.get?
  end

end

And finally the preference controller 最后是偏好控制器

class PreferencesController < ApplicationController
  before_action :set_preference, only: [:show, :edit, :update, :destroy]

  # GET /preferences
  # GET /preferences.json
  def index
    @preferences = Preference.all
  end

  # GET /preferences/1
  # GET /preferences/1.json
  def show
  end

  # GET /preferences/new
  def new
    @preference = Preference.new
  end

  # GET /preferences/1/edit
  def edit
  end

  # POST /preferences
  # POST /preferences.json
  def create
    @preference = Preference.new(preference_params)

    respond_to do |format|
      if @preference.save
        format.html { redirect_to @preference, notice: 'Preference was successfully created.' }
        format.json { render :show, status: :created, location: @preference }
      else
        format.html { render :new }
        format.json { render json: @preference.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /preferences/1
  # PATCH/PUT /preferences/1.json
  def update
    respond_to do |format|
      if @preference.update(preference_params)
        format.html { redirect_to @preference, notice: 'Preference was successfully updated.' }
        format.json { render :show, status: :ok, location: @preference }
      else
        format.html { render :edit }
        format.json { render json: @preference.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /preferences/1
  # DELETE /preferences/1.json
  def destroy
    @preference.destroy
    respond_to do |format|
      format.html { redirect_to preferences_url, notice: 'Preference was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_preference
      @preference = Preference.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def preference_params
      params.require(:preference).permit(:user_id, :institute_id, :preference_value, :wei_preference_value,
      :accepted)
    end
end

In your User model you should create a relation to the Preference model User模型中,您应该创建与Preference模型的关系

class User < ApplicationRecord
  . . .
  has_many :preferences
  . . . 
end

As long as Preference has the column user_id to identify the User it belongs to, then this should work by adding just that one line. 只要“ Preference具有“ user_id ”列来标识其所属的User ,则应该仅添加该行即可。

Then, in your view you can use it like this: 然后,在您的视图中,您可以像这样使用它:

<% @current_user.preferences.each do |preference| %>
  <tr>
    <td><%= preference.institute_id %></td>
      <td><%= preference.preference_value %></td>
      <td><%= link_to 'Bearbeiten', edit_preference_path(preference) %></td>
      <td><%= link_to 'Löschen', preference, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

You should read up more on Active Record Associations , they will help you a lot and are an important part of Rails. 您应该阅读有关Active Record Associations的更多信息,它们会为您提供很多帮助,并且是Rails的重要组成部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM