1

I'm building a rails app where a user model has several has_many relationships with other models.

class User < ActiveRecord::Base

    has_many :model_2s
    has_many :model_3s
    has_many :model_4s

end

I am then creating a profile page where I display data from each of these models for the current user. I am doing this using a separate controller - profiles_controller.rb

In the profiles controller I am creating instance variables for each of these models based on the current user:

class ProfilesController < ApplicationController

    @user = User.find(params[:id])
    @model_2s = @user.model_2s.all
    @model_3s = @user.model_3s.all
    @model_4s = @user.model_4s.all
end

I am then able to display data from these instance variables in the show view for profiles. I do this by calling an each method.

The functionality I am now trying to add is to show some default data (like Lorem Ipsum placeholder text) for fields that the user has not filled in.

My issue is that I cannot figure out how to check if a particular field in these instance variables is empty.

For example, I would like something along the lines of:

<% if @model_2s.field_1.empty? %>
    <p>Lorem Ipsum</p>
<% else %>
    <%= @model_2s.field_1 %>
<% end %>

However this gives an "undefined method 'field_1'... " error.

I know how to check for @model_2s.any? to confirm the instance variable itself is present, but I want to be able to do a conditional check at the next level down - the fields within the instance variable.

4

2 回答 2

1

不确定您在视图中在做什么,但如果您想访问类似的东西,肯定需要循环每个结果集field_1

<% @model_2s.each do |m| %>

    <% if m.field_1.empty? %>
        <p>Lorem Ipsum</p>
    <% else %>
        <%= m.field_1 %>
    <% end %>

<% end %>

这也处理@model_2s空的情况。

于 2013-05-27T09:17:17.997 回答
0

试试这个方法

<% if @model_2s %>
 <% @model_2s.each do |model_2| %>
  <% if model_2.field_1.empty? %>
      <p>Lorem Ipsum</p>
  <% else %>
      <%= model_2.field_1 %>
  <% end %>
 <% end %>
<% end %>

它将在循环内..

于 2013-05-27T09:05:35.677 回答