将参数从控制器发送到模型导轨

时间:2016-09-02 09:37:26

标签: ruby-on-rails api model controller

我正在参加Meetup Api。 我想将API中的一些会议保存到我的数据库中。 保存会议取决于传递到控制器的视图的参数:

  <%= link_to 'See conferences', conferences_path(:title => "ParisRb")%> |

然后我打电话给好方法,寻找从api收到的所有好会议(与params比较)。 我希望这些方法非常通用,并且能够保存任何会议,而不仅仅是“ParisRb&#39;。

所以我修改了这个目标中的所有方法,但有一个我无法修改,我不知道如何。

这是我的全部代码。我想要修改的是self.conferences_filter(data),它应该从控制器接收参数而不是“ParisRb”。但我知道将控制器中的参数传递给模型并不是一个好习惯。所以欢迎任何想法:)

LIB / api_meetup.rb

class ApiMeetup
  BASE_URI = "https://api.meetup.com"

  def events(urlname)
    HTTParty.get(BASE_URI + "/#{urlname}/events")
  end
end

conferences_controller.rb

def index
    #call to the API
    response = ApiMeetup.new.events(params[:title])
    api_data = JSON.parse(response.body)

    filtered_conferences = Conference.conferences_filter(api_data)
    conferences = Conference.save_conferences_from_api(filtered_conferences)

    @conferences = conferences.current_conferences
  end  

conference.rb

#Keep only requested conferences
  def self.conferences_filter(data)
    requested_conferences = []
    data.each do |event|
      if event["name"].include?('ParisRb') #This should receive params[:title] instead of 'ParisRb'
        requested_conferences << event
      end
    end
    requested_conferences
  end

  #Save requested conferences from the Meetup API
  def self.save_conferences_from_api(conferences)
    # data = data_from_api
    conferences.each do |line|
      conference = self.new
      conference.title = line['name']
      conference.date = format_date(line['time'])
      conference.url = line['link']
      if conference.valid?
        conference.save
      end
    end
   self.all
  end 

1 个答案:

答案 0 :(得分:0)

实际上这很明显。 我只需要将参数传递给我的方法:

filtered_conferences = Conference.conferences_filter(api_data, params[:title])

#Keep only requested conferences
  def self.conferences_filter(data, title)
    requested_conferences = []
    data.each do |event|
      if event["name"].include?(title)
        requested_conferences << event
      end
    end
    requested_conferences
  end