gpt4 book ai didi

ruby-on-rails - rails : Better way to create variables for views

转载 作者:数据小太阳 更新时间:2023-10-29 07:56:47 26 4
gpt4 key购买 nike

我对 Ruby 和 Rails 完全陌生。目前,我正在使用辅助方法。我如何在我的模型“用户”中编写与此相同的代码,以便从 Controller 和 View 访问所有这些变量?

在 helper 中以这种方式编写代码是 100% 有效的:

module HomeHelper

def init(user_id)
@friends = Array.new
@followers = Array.new

@user = User.find_by_id(user_id) #Get User
@friends = @user.users #Get all his friends
#
@statuses = Array.new #
@friends.each do |friend| #
@statuses += friend.statuses #Get all statuses for 'a' friend, then loop
end #
@statuses += @user.statuses #
@statuses = @statuses.sort_by {|status| status.created_at}.reverse!

@friendsof = Array.new
@filtered_friendsof = Array.new

@friends.each do |friend|
@friendsof += friend.users
end
@friendsof.each do |friendof|
unless (@friends.include?(friendof))
if @user != friendof
@filtered_friendsof << friendof
end
end
end
end

@filtered_friendsof = @filtered_friendsof.uniq

end

Controller

class HomeController < ApplicationController
def index
@user_id=3
end
end

型号:

class User < ActiveRecord::Base
has_many :statuses
has_and_belongs_to_many(:users,
:join_table => "user_connections",
:foreign_key => "user1_id",
:association_foreign_key => "user2_id")
#has_many :user_connections
end

最佳答案

家庭 Controller :

class HomeController < ApplicationController
def index
@user = User.find(3)
end
end

用户模型:

class User < ActiveRecord::Base
has_many :statuses
has_and_belongs_to_many :friends,
:class_name => 'User'
:join_table => "user_connections",
:foreign_key => "user1_id",
:association_foreign_key => "user2_id"

def combined_statuses
(friends.map(&:statuses) + statuses).flatten.
sort_by {|status| status.created_at}.reverse!
end
end

现在,您不需要辅助方法,在您看来,您可以使用:

@user.friends # instead of @friends
@user.combined_statuses # instead of @statuses

我会让您弄清楚其余部分,但我希望您了解将逻辑插入模型的总体思路。

关于ruby-on-rails - rails : Better way to create variables for views,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12873917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com