简体   繁体   中英

if statement in ruby loop editing properties

I have two database tables, user and product When the user creates a product the user.id is placed into the product table under product.user_id

I'm writing a loop to displays all products "belonging" to the currently signed in user, it looks like this so far.

<% @product.each do |p| %>
 <% if product.user_id = user.id %>
 <tr>
    <td><%= user.id %></td>
    <td><%= product.user_id %></td>
    <td><%= product.id %></td>
    <td><%= product.name %></td>
</tr>
  <% end %>
<% end %>

If the currently signed in user is user 2 for example, instead of filtering all products that don't have a user.id of 2 it just changes the product.user_id for every product to 2 so that the returned table looks like so.

2 2 1
2 2 2
2 2 3
2 2 4

Without the if statement it returns the full product listing with all the correct properties.

您应该使用== not =

<% if product.user_id == user.id %>

Here is your complete solution

<% @product.each do |p| %>
 <% if p.user_id == user.id %>
 <tr>
    <td><%= user.id %></td>
    <td><%= p.user_id %></td>
    <td><%= p.id %></td>
    <td><%= p.name %></td>
</tr>
  <% end %>
<% end %>

However I don't know what is going on in your controller but you could probably save a lot of effort by filtering out on the current user's products in the controller prior to serving that @product instance variable to the view. Maybe try a query like this:

user_id = current_user.id #assuming you have access to a method like this
@product = Product.where(user_id: user_id)

EDIT philomor is correct. You should add a has many relationship on user see below.

#app/models/user.rb
class User < ActiveRecord::Base
  has_many :products
end

#app/models/product.rb
class Product < ActiveRecord::Base
  belongs_to :user
end

However not that you have this relationship you want to be carful that when you call it you don cause an N+1 query . To avoid this do the following when fetching all of a user's products

@products = User.find(params[:user_id]).includes(:products).products

使用比较运算符==并且if语句应类似于

<% if p.user_id = user.id %>

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