简体   繁体   中英

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. 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? user_url

for line 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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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