如何渲染我的项#在用户配置文件中显示部分?

时间:2015-06-01 15:38:03

标签: ruby-on-rails devise

大家早上好!我正在进行rails分配,我在用户配置文件中将我的项目部分渲染时遇到了一些麻烦。我认为问题是@item变量在用户的视图中没有初始化?每当我向用户的列表中添加新项目时,都应将其归于他/她,并显示出来。此时,我知道该项目正在创建并且特定于用户,但未显示。以下是我的一些代码:

物品型号:

Dim objIniFile As New IniFile("c:\data.ini")
objIniFile.WriteString("Settings", "ClockTime", "12:59")
Dim strData As String = _
    objIniFile.GetString("Settings", "ClockTime", "(none)")

用户模型:

class Item < ActiveRecord::Base
  belongs_to :user
end

物品管制员:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  has_many :items
end

用户控制器:

class ItemsController < ApplicationController
  def new
    @user = User.find(params[:user_id])
    @item = Item.new
  end

  def create
    @user = User.find(params[:user_id])
    @item = Item.new(params.require(:item).permit(:name))
    @item.user_id = @user.id
     if @item.save
       flash[:notice] = "Item was saved."
       redirect_to [@user, @item]
     else
       flash[:error] = "There was an error saving the item. Please try again."
       render :new
     end
   end

   def show
     @user = User.find(params[:user_id])
     @item = Item.find(params[:id])
   end
end

_item.html.erb partial:

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    @item = @user.items
  end

  private
   def user_params
     params.require(:user).permit(:name, :email)
   end
end

此时,它仅显示个人资料视图中的项目。

用户#show:

<%= @item.name %>
<br>

感谢您的帮助,没有SO社区,我无法走到这一步。

3 个答案:

答案 0 :(得分:1)

您可以像这样修改代码:

users_controller.rb

def show
  @user = User.find(params[:id])
  @items = @user.items
end

用户/ show.html.erb

<div class="col-md-6">
   <h2>User's To-Do List</h2>
    <%= render partial: 'items/item', locals: {items: @items} %>
</div>

itemss / _item.html.erb

<% items.each do |item| %>
  <%= item.name %>
<% end %>

答案 1 :(得分:0)

你可以试试这个,我希望这会对你有帮助。

用户控制器:

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    @items = @user.items
  end

  private
   def user_params
     params.require(:user).permit(:name, :email)
   end
end

_item.html.erb partial:

<% @items.blank? %>
  <% @items.each do |item| %>
    <%= item.name %>
  <% end %>
<% else %>
 <h2> No Items Found. </h2>
<% end %>

用户#显示:

<div class="col-md-6">
  <h2>User's To-Do List</h2>
  <%= render 'items/item', object: @items %>
</div>

答案 2 :(得分:0)

尝试更改以下内容:

<强> users_controller.rb

 def show
   @user = User.find(params[:id])
   @items = @user.items
 end

<强> _item.html.erb

 <% unless items.blank? %>
   <% items.each do |it| %>
     <%= it.name %>
     <br/>
   <% end %>
 <% end %>

<强> show.html.erb

 <%= render 'items/item', items: @items %>