gpt4 book ai didi

ruby-on-rails - 嵌套(同时未嵌套)资源更好的方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:12:57 24 4
gpt4 key购买 nike

我有两个这样的模型

class Plan < ActiveRecord::Base
belongs_to :profile

class Profile < ActiveRecord::Base
has_many :plans

路线如:(我需要)

resources :profiles do
resources :plans
end
resources :plans

所以,跟进ruby-on-rails - Problem with Nested Resources , 我已经像这样制作了我的 PLANS 索引 Controller ,以同时工作 NESTED 和 UNESTED (我现在找到的唯一方法):

def index
if params.has_key? :profile_id
@profile = Profile.find(params[:profile_id])
@plans = @profile.plans
else
@plans = Plan.all
end

有更简洁的方法吗?

在这种情况下我有另一个模型,将所有操作放在所有 Controller 中以像这样表现很麻烦。

最佳答案

你给了我一个想法:

模型/用户.rb:

class User < ActiveRecord::Base
has_many :posts
attr_accessible :name
end

模型/post.rb:

class Post < ActiveRecord::Base
belongs_to :user
attr_accessible :title, :user_id
end

Controller /posts_controller.rb:

class PostsController < ApplicationController
belongs_to :user # creates belongs_to_user filter

# @posts = Post.all # managed by belongs_to_user filter

# GET /posts
# GET /posts.json
def index
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
end

现在是实质内容:

controllers/application_controller.rb:

class ApplicationController < ActionController::Base
protect_from_forgery

def self.belongs_to(model)
# Example: model == :user
filter_method_name = :"belongs_to_#{model}_index" # :belongs_to_user_index
foreign_key = "#{model}_id" # 'user_id'
model_class = model.to_s.classify # User

class_eval <<-EOV, __FILE__, __LINE__ + 1
def #{filter_method_name} # def belongs_to_user_index
if params.has_key? :'#{foreign_key}' # if params.has_key? :user_id
instance_variable_set :"@#{model}", # instance_variable_set :"@user",
#{model_class}.find(params[:'#{foreign_key}']) # User.find(params[:user_id])
instance_variable_set :"@\#{controller_name}", # instance_variable_set :"@#{controller_name}",
@#{model}.send(controller_name.pluralize) # @user.send(controller_name.pluralize)
else # else
instance_variable_set :"@\#{controller_name}", # instance_variable_set :"@#{controller_name}",
controller_name.classify.constantize.all # controller_name.classify.constantize.all
end # end
end # end
EOV

before_filter filter_method_name, only: :index # before_filter :belongs_to_user_index, only: :index
end
end

如果您有 Ruby 元编程的概念,那么理解代码并不复杂:它声明了一个 before_filter,它声明了从 Controller 名称和关联中推断名称的实例变量。它仅针对索引操作实现,这是唯一使用复数实例变量版本的操作,但为其他操作编写过滤器版本应该很容易。

关于ruby-on-rails - 嵌套(同时未嵌套)资源更好的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14522513/

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