Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Railscasts PRO #213中link_to的格式與 #107

Open
ghost opened this issue Dec 16, 2015 · 5 comments
Open

Railscasts PRO #213中link_to的格式與 #107

ghost opened this issue Dec 16, 2015 · 5 comments

Comments

@ghost
Copy link

ghost commented Dec 16, 2015

大家好,我最近看了Railscasts PRO #213(https://www.youtube.com/watch?v=ndBKSjAbemo)
有個問題
問題:裡面在做切換月份的箭頭時,約影片8:50,程式碼如下

<%= link_to "<", date: @date.prev_month %>
<%= @date.strftime("%B %Y") %>
<%= link_to ">", date: @date.next_month %>

我不太懂這個link_to的格式,link_to後面沒有放其他url,不是應該沒有動作嗎?

@GeorgioWan
Copy link

date: @date.prev_monthdate: @date.next_month
影片8:59 透過 params[:date] 變更了 @Date 囉!可以觀察一下他點擊後,網址變動了~

詳細範例可參考 link_to helper 🎅

@ghost
Copy link
Author

ghost commented Dec 18, 2015

GeorgioWan 你好,謝謝你的回答。
我知道網頁會將date: @date.next_month當作參數傳給controller中的@Date,然後再送到頁面中。
不過我不懂的是link_to(body, url, html_options = {}),中的url在這邊沒有看到,還是是另一種格式,所以有預設的url呢?

@zetavg
Copy link
Member

zetavg commented Dec 18, 2015

我想他是用了像這個範例

link_to(body, url_options = {}, html_options = {})
  # url_options, except :method, is passed to url_for

的格式吧!link_to ">", date: @date.next_month 並不是省略了第二個 url 參數 (Ruby method 傳入的參數必定是照順序排下來,不會因為型別不對就認定是中間的某個參數消失了),而是變成了 url_options,並傳入 { date: @date.next_month } 做為 url_options

而這個 url_options 要怎麼用呢?追蹤 source code / 文件可以發現在 url_for 有列出他的用法。在此例中,他會變成如 ?date=2012-01-01

@GeorgioWan
Copy link

@RuBeginner Hello!
我試了這個範例,發現
= link_to "<", date: @date.prev_month 編譯出來的 url 是當前頁傳遞 date 變數
就像是 = link_to "user", @user 較為晚整的寫法為 = link_to "user", user_path(@user)
只是當中省略的是什麼 path 我就不清楚了,我暫時是把它當慣例,還請眾前輩指點XDD

@ghost
Copy link
Author

ghost commented Dec 20, 2015

謝謝Neson給的資訊url_for,其中在看了url_options的解釋就比較瞭解了!
Hook overridden in controller to add request information with default_url_options. Application logic should not go into url_options.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants