简体   繁体   中英

ruby-on-rails: passing params through a route & link_to

I have a name route:

map.up_vote 'up_vote', :controller => 'rep', :action => 'up_vote

But up_vote requires two arguments to be passed in, postID and posterID and I can't seem to figure how to do that in a partial, but in an integration test I have no issues.

Partial:

link_to 'Up Vote', up_vote_path, {:postID => session[:user_post_id], :postersID => session[:poster_id]} 

Integration test:

post up_vote_path,{:postID => @latest.id,:postersID => users(:bob).id} (this works ok)

1) What is going on the in the partial?

2) What changes can I make to my tests to catch this?

A question: why are you passing your session variables in a link? You can get them directly from the session...

I don't know if there are any special reasons to put :user_post_id and :poster_id in the session but I recommend you two things:

1) Pass your variables in urls , sessions can be evil (try hitting back, refresh and forward on your browser)

2) Use resources in your URLs / controller actions logic.

Example (valid only if I got it right and you're voting an user's post):

routes:

map.resources :users do |user|
  user.resources :posts do |post|
    post.resource :vote
  end
end

So you can have this url:

/users/:id/posts/:post_id/vote

And the link path:

link_to "Up", user_post_vote_path(@user, @post), :method => :create

I putting @user and @post instead of the integers because path methods accept them and you can build a shorter version with:

link_to "Up", [@user, @post, :vote] # or [:vote, @post, @user]

Implementing:

class VoteController ....
  def create
    # do your stuff here
  end
end

This way it will be easier and RESTful.

Ryan Bates got a great episode on resources, it definately worths a look.

You want to pass your params in the ..._path

link_to "Up Vote", up_vote_path(:postID => session[:user_post_id], :postersID => session[:poster_id])

The integration test is written out differently than the link_to since your testing the act.

post "to" up_vote_path, "with these" {params}

Also since your doing a POST, you will want to add the appropriate :method option to the link_to

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