Ruby on Rails模型文件中的条件语句

时间:2015-10-14 05:22:56

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 rails-models

我们是否可以在我们的Rails模型文件中编写条件语句,例如在我的情况下,如果我想根据用户是否在我的Customer.rb文件中使用singned_in来实现一些验证。

if user_signed_in?  // if signed_in is true
     //my validation code here

然后是一些特殊的验证和

else !user_signed_in? // if signed_in is false
     //my validation code here

2 个答案:

答案 0 :(得分:3)

current_useruser_signed_in?等在模型中不可用。

Rails 3 devise, current_user is not accessible in a Model ?

简而言之,您的以用户为中心的条件应该在控制器中,模型是拉动&仅操作数据 ...

enter image description here

我一直发布这张图片;它显示了标准 MVC 框架的外观。 Rails MVC框架...向您展示模型和其他元素如何协同工作以使其正常工作。

正如您所看到的,控制器就像“集线器”一样将它们粘合在一起。为了使您的应用程序保持正确的结构,理想情况下,您希望将中级逻辑放入控制器,将数据级逻辑放入模型中,并将表面逻辑放入您的视图中。

EG:

#Model
class Products
   belongs_to :user
end

#controller
def index
   @products = user_signed_in? ? current_user.products : Product.all
end

#view
<% @products.each do |product| %>
   <%= product.name if product.name %>
<% end %>

您需要的答案是指定所需的验证逻辑,允许您在控制器/模型中应用所需的数据

如果您想在模型中使用用户验证,则必须在控制器级别使用条件并将结果传递给模型:

#app/controllers/users_controller.rb
class UsersController < ApplicationController
   def create
      @user = User.new user_params
      @user.online = user_signed_in?
   end

   private

   def user_params
      params.require(:user).permit(:x, :y, :z)
   end
end

#app/models/user.rb
class User < ActiveRecord::Base
   validates :online, presence: true
end

答案 1 :(得分:0)

这样的东西?

function changeButtonText(button, text){ // jQuery it $button = $(button); // get orinal css'es oooon = $button.css('text-align'); doooo = $button.css('overflow'); treee = $button.css('white-space'); $button.css('text-align', 'left').css('overflow', 'hidden').css('white-space', 'nowrap');; // get new width first $tmpBtn = $button.clone().append(text).css('opacity', '0.0').appendTo('body'); newWidth = $tmpBtn.outerWidth(); $tmpBtn.remove(); // now stretch the button out $button.animate({width: newWidth+"px"}); // fade texts into the butt $button.append('<span style="display:none">'+text+'</span>'); $btnText = $button.find('span').fadeIn('slow'); return { 'text-align':oooon, 'overflow':doooo, 'white-space':treee }; }