Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

ruby on rails - Passing parameters from view to controller

I got a bit of a newbie question. I'm trying to pass a variable from my view to my controller. Is there anyway my method in my controller can receive variables from my view?

Post view: show.html.erb:
....
<%=link_to "Add relationship", :method => :add_relationship(@rela) %>

Controller: post.controller.rb:

 def add_relationship(rela)
  @post = Post.find(params[:id])

  if current_user.id == @post.user_id
    @post.rel_current_id = rela.id
    @post.save
    redirect_to relationships_url
  else
    redirect_to posts_url, :notice => "FY!"
  end
end

Thanks in advance :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can add information to the params hash right through the link_to. I'm not sure exactly what you are trying to do but I did something like this recently to add the type of email I wanted when I link to the new email

<%= link_to 'Send Thanks', new_invoice_email_path(@invoice, :type => "thanks") %>

Now my params looks like:

{"type"=>"thanks", "action"=>"new", "controller"=>"emails", "invoice_id"=>"17"}

I can access the type via the params

email_type = params[:type]

Instead of a string, if you pass in the instance variable @rela you will get the object_id in the params hash.

Per the comment below, I'm adding my routes to show why the path new_invoice_email_path works:

resources :invoices do
  resources :emails
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...