简体   繁体   中英

Rails4 how to pass variable within controller

I'm using Ransack in a Rails 4 app to search records on an index list.

I then have a button on that index list linking to a scoresgraph page.

I want to use the @scores from the index in the scores graph .

Here is the scores controller:

def index
  @search = current_user.scores.notarchived.search(params[:q])
  @scores = @search.result
end

def scoresgraph
  @scores = params[:scores]
end

This is the button in the index page:

<%= link_to 'Graph', scores_scoresgraph_path(:scores => @scores), :class => 'btn btn-xs btn-primary' %>

But, I'm getting: undefined method `order' for "#Score::ActiveRecord_AssociationRelation:0x007fb5bdbf9a08":String

You should extract what is inside index into a separated method:

def index
  @scores = score
end

def scoresgraph
  @scores = score
end

private

def search
  @search ||= current_user.scores.notarchived.search(params[:q])
end

def score
  search.result
end

If this does not work, it may be because in the scoresgraph you don't have reference to the old variables, so you should change the link_to to:

<%= link_to 'Graph', scores_scoresgraph_path(q: 'same q as the index'), :class => 'btn btn-xs btn-primary' %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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