I'm trying to do something I thought easy and natural but I'm struggling..
On the homepage of my website, I want a select containing a list of users. After selecting a user and clicking on a button, it should go to the show action of the User controller page.
I searched and 开发者_如何学运维found differents answers that I don't find very elegant:
- using AJAX http://www.mail-archive.com/rubyonrails-talk@googlegroups.com/msg36368.html
- using an observe_field to modify the url in the html
Is there a better way doing this?
What would be the best way?
I would probably do this with jQuery...or just plain old javascript.
$("#button_id").click(function(){
window.location = '/users/' + $("#select_list_id").children("option:selected").val();
});
That should add an onclick method to the button and then forward you to '/user/12345'.
You could do the same thing in plain javascript if you aren't using jquery, but it's a little more involved.
<script type="javascript">
function goToUsersPage() {
list = document.getElementById('select_list_id')
window.location = '/users' + list.options[selectedIndex].value;
}
</script>
Then you need to add the function call to the onclick method of your button.
<input type='button' onclick='goToUsersPage();' value='Go!'/>
Instead of using javascript you could just make the select and button a form and have an action in the controller that takes the user id and redirects to the user's page.
Something like:
def user_form
@user = User.find(params[:id])
respond_to do |format|
format.html { redirect_to(@user) }
end
end
精彩评论