简体   繁体   English

在 model + rails 5 中访问参数

[英]Access params inside model + rails 5

The code is as follows代码如下

 def update
    # params = {"from_zip"=>"28803", "lane_week_day_names"=>["Wednesday", "Monday"]}
    @lane.assign_attributes(params)
    
    return unless @lane.valid?

    # rest of logic
  end

Model is defined as follows Model定义如下

validate :duplicate_lane
has_many :lane_week_days

 def lane_week_day_names
    lane_week_days.map(&:day)
 end

 def lane_week_day_names=(daynames)
    Date::DAYNAMES.each do |dayname|
      existing = lane_week_days.find { |week_day| week_day.day == dayname }
      if daynames.include?(dayname)
        lane_week_days.build(day: dayname) if existing.blank?
      else
        existing&.mark_for_destruction
      end
   end
 end

Model validation is defined as follows Model验证定义如下

def duplicate_lane
   #need to get lane_week_day_names form the params
   #compare lane_week_day_names from the params with existing records

    errors.add(:base, "Invalid")
  end

I need to get the lane_week_day_names which is available in params to be accessed inside the model. Any idea on how to achieve this?我需要获取参数中可用的 lane_week_day_names,以便在 model 中访问。关于如何实现这个的任何想法?

you can use this, but you have to change the params names to another name because you have a method with the same name.你可以使用它,但你必须将参数名称更改为另一个名称,因为你有一个具有相同名称的方法。

# app/models/lane.rb

attr_accessor :another_params_name

def duplicate_lane
  self.another_params_name # you'll get the value here.
end

Thanks:)谢谢:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM